2016-06-14 74 views
22

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

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

的文档以下内容:http://redux.js.org/docs/api/createStore.html

,但它不工作,我不明白为什么。

回答

41

它需要的第二个参数createStore

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

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

const store = createStore(
    rootReducer, 
    initialState 
); 
-3
  1. 你有语法错误
  2. 只是把初始状态行动的创建者和调用它componentWillMount
  3. 使减速机:出口默认功能(){return todo:['read','eat','sleep'];} 4:让你清楚 es6用于代码吹

//es6 is used in code below check code below for simple example 
 

 

 
import { combineReducers } from 'redux' 
 
import todos from './todos' 
 
import visibilityFilter from './visibilityFilter' 
 

 
const todoApp = combineReducers({ 
 
    todos, 
 
    visibilityFilter 
 
}) 
 

 
export default todoApp 
 
    
 
//this is the same as 
 
const todoApp = combineReducers({ 
 
    todos: todoReducer, 
 
    visibilityFilter: visibilityFilterReducer 
 
}) 
 
    
 
export default todoApp

+0

OP问:“我想知道如何设置一个商店的初始状态在REDX。” – ctrlplusb

13

您可以在减速机(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 
})