Redux:我们应该在哪里为初始化状态设置反应应用程序
例如:我希望当反应应用程序被打开时,它将创建一个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 = "*";
但是,当我反应过来的应用程序开始时,我没有看到“sampleString”键在这个redux树。请帮我弄清楚哪一部分是我错了。
感谢
导出此函数:
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 };
};
让调用该函数X
。你应该像这样来调用它:
X({sampleString: "*"});
你必须避免使用像幽会这一个改变状态:
store.getState().sampleString = "*";
谢谢。我明白了。这里是我的代码:'const initialState = window .__ INITIAL_STATE__; const {store,customHistory} = createStore(initialState); '当我改变'const initialState = {sampleString:“*”}''。我遇到错误。 –
错误是:“异想要的键”sampleString“在减速器接收到的以前的状态中找到。预期会找到一个已知的减速键而不是:”location“。意外的键将被忽略。 –
请参阅:https://*.com/questions/37998281/react-redux-unexpected-key-passed-to-create-store。您没有在减速器中正确定义您的sampleString键。 – lilezek
你必须派一些行动改变状态。我认为这是触发状态更改的唯一方法 –
其中定义了传递给该函数的initialState?该变量应该保留你的密钥。如果你想让它成为最初的状态,你不应该改变状态。 – lilezek
@EQuimper能否解释为什么减持可以解决我的问题的更多细节。正如我所知,redux-persist帮助我们将redux树保存到本地存储。 –