例如:我希望当反应应用程序被打开时,它将创建一个key为“user”的redux树,并且值是用户对象从LocalStorage进行解析(当用户被登录)。Redux:我们应该在哪里为初始化状态设置反应应用程序
我想我应该把createStore
。这是我创建存储代码:
import { applyMiddleware, compose, createStore } from 'redux';
import thunk from 'redux-thunk';
import { browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import makeRootReducer from './reducers';
import { updateLocation } from './location';
export default (initialState = {}) => {
const middleware = [thunk];
const enhancers = [];
let composeEnhancers = compose;
const store = createStore(
makeRootReducer(),
initialState,
composeEnhancers(applyMiddleware(...middleware), ...enhancers)
);
window.store = store;
store.asyncReducers = {};
store.unsubscribeHistory = browserHistory.listen(updateLocation(store));
// const history = syncHistoryWithStore(browserHistory, store);
// console.log(history);
return { store: store, history: null };
};
因此,作为权作为存储中创建,我初始化对象:
const store = createStore(
makeRootReducer(),
initialState,
composeEnhancers(applyMiddleware(...middleware), ...enhancers)
);
store.getState().sampleString = "StackOverFlow";
但是,当我反应过来的应用程序开始时,我没有看到“sampleString”键在这个redux树。请帮我弄清楚哪一部分是我错了。
感谢
你必须派一些行动改变状态。我认为这是触发状态更改的唯一方法 –
其中定义了传递给该函数的initialState?该变量应该保留你的密钥。如果你想让它成为最初的状态,你不应该改变状态。 – lilezek
@EQuimper能否解释为什么减持可以解决我的问题的更多细节。正如我所知,redux-persist帮助我们将redux树保存到本地存储。 –