2016-06-14 91 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 
}) 
相關問題