根据查询字符串参数初始化存储



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

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

最初,我用一个包裹在例如中的组件来做到这一点withRouter(InitStoreFromQueryString ),但是我最终得到的组件什么都不渲染,例如:<InitStoreFromQueryString />并简单地在componentDidMount上调度操作。这看起来真的很尴尬。

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

如果您使用的是 react-router,则可以使用历史记录模块来跟踪位置更改。您可以将侦听器添加到历史记录对象,并在位置更改时调度操作。

示例(未测试(:

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
});

最新更新