如何在 redux 中设置初始状态

新手上路,请多包涵

我试图弄清楚如何在 redux 中为商店设置初始状态。我以 https://github.com/reactjs/redux/blob/master/examples/todos-with-undo/reducers/index.js 为例。我试图修改代码,以便 todos 具有初始化的值。

 const todoApp = combineReducers({
  todos,
  visibilityFilter
}, {
  todos: [{id:123, text:'hello', completed: false}]
})

按照文档: http ://redux.js.org/docs/api/createStore.html

但它不起作用,我不太清楚为什么。

原文由 Saad 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 604
2 个回答

它必须是 createStore 的第二个参数:

 const rootReducer = combineReducers({
  todos: todos,
  visibilityFilter: visibilityFilter
});

const initialState = {
  todos: [{id:123, text:'hello', completed: false}]
};

const store = createStore(
  rootReducer,
  initialState
);

原文由 ctrlplusb 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以在减速器中设置初始状态。

 const initialTodos = [{id:123, text:'hello', completed: false}]

// this is the ES2015 syntax for setting a default value for state in the function parameters
function todoReducer(state = initialTodos, action) {
  switch(action.type) {
    ...
  }
  return state
}

const todoApp = combineReducers({
  // todos now defaults to the array of todos that you wanted and will be updated when you pass a new set of todos to the todoReducer
  todos: todoReducer,
  visibilityFilter
})

原文由 jmancherje 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进