how to set initial state in redux

2019-01-17 19:30发布

I'm trying to figure out how to set an initial state for a store in redux. I'm using https://github.com/reactjs/redux/blob/master/examples/todos-with-undo/reducers/index.js as an example. I tried to modify the code such that the todos had a value initialized.

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

following the doc: http://redux.js.org/docs/api/createStore.html

but it's not working, and I'm not quite sure why.

2条回答
ゆ 、 Hurt°
2楼-- · 2019-01-17 19:57

It needs to be the second argument to createStore:

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

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

const store = createStore(
  rootReducer, 
  initialState
);
查看更多
淡お忘
3楼-- · 2019-01-17 19:57

You can set the initial state in the reducer(s).

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
})
查看更多
登录 后发表回答