如何在redux中设置初始状态

问题描述 投票:33回答:3

我正在试图弄清楚如何在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

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

reactjs redux react-redux
3个回答
58
投票

它需要是createStore的第二个参数:

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

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

const store = createStore(
  rootReducer, 
  initialState
);

26
投票

您可以在reducer中设置初始状态。

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

0
投票

根据@ctrlplusb的回答,这个工作的原因是因为

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

第一个todos是一个键,它将第二个todos设置为减速器的返回值。减少器总是在创建商店时运行一次。这会初始化您的全局商店。

创建商店时会调度一个操作。这就是每个组合减速器中提供的初始状态在商店中初始化的方式。如果你检查redux dev工具,你会看到发送的第一个动作是“@@ redux / INIT {something}”

在redux的文档中,靠近文件的末尾,有一个调度({type:ActionTypes.INIT})

看到这里https://github.com/reduxjs/redux/blob/master/src/createStore.js#L281-L284

看到这个问题/我在stackoverflow上做出的澄清回应:Different ways of initializing a react redux store's initial global state?

© www.soinside.com 2019 - 2024. All rights reserved.