代码之家  ›  专栏  ›  技术社区  ›  dragonfly

基于查询字符串参数初始化存储

  •  1
  • dragonfly  · 技术社区  · 8 年前

    可以使用查询字符串参数访问我的应用程序,这些参数包含一些初始设置,例如。 ?accountId=PL123454252 .

    完成后,我需要初始化存储,即将查询字符串中的关联帐户对象放入存储。

    最初,我是用一个包裹着的组件做的,比如。 withRouter(InitStoreFromQueryString ) 然而,我最终得到的组件只是不呈现任何内容,例如: <InitStoreFromQueryString /> 并简单地对 componentDidMount .这看起来很尴尬。

    有没有更好的方法来达到同样的效果,即在启动时加载应用程序时,根据查询字符串参数初始化存储?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Ori Drori    8 年前

    如果您使用的是react路由器,则使用 history 跟踪位置变化的模块。你可以添加一个 listener 并在位置更改时分派操作。

    示例(未测试):

    import createStore from "./store";
    import createHistory from "history/createBrowserHistory";
    
    const store = createStore();
    const history = createHistory();
    
    const unlisten = history.listen((location) => {
      const accountId = extractFromLocation(location.search); // extract the accountId from the location query
      if(store.getState().accounts[accountId]) return; // if in store do nothing
      store.dispatch(updateAccountData(accountId)); // update the store with the new account
    });