Redux:我们应该在哪里放置react应用程序的初始化状态

时间:2017-08-17 18:56:31

标签: reactjs redux

例如:我想在打开react app时,它会创建一个redux树,键是“user”,value是用户对象是从LocalStorage解析的(当用户登录时)。

我想我应该加入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";

但是当我的react应用程序启动时,我在这个redux树中看不到“sampleString”键。请帮我弄清楚哪个部分我错了。

由于

1 个答案:

答案 0 :(得分:1)

您已导出此功能:

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: "StackOverflow"});

必须避免使用像这样的分配来改变状态:

store.getState().sampleString = "StackOverFlow";