2016-06-14 35 views
22

Sto cercando di capire come impostare uno stato iniziale per un negozio in redux. Sto usando https://github.com/reactjs/redux/blob/master/examples/todos-with-undo/reducers/index.js come esempio. Ho provato a modificare il codice in modo tale che i todos avessero un valore inizializzato.come impostare lo stato iniziale in redux

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

seguendo il doc: http://redux.js.org/docs/api/createStore.html

ma non funziona, e io non sono del tutto sicuro perché.

risposta

41

ha bisogno di essere il secondo argomento createStore:

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

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

const store = createStore(
    rootReducer, 
    initialState 
); 
-3
  1. avete errore di sintassi
  2. appena messo stato iniziale in atto creatore e lo chiamano il componentWillMount
  3. fare un riduttore: export funzione predefinita() {return todo: ['read', 'eat', 'sleep'];} 4: per chiarire es6 viene utilizzato nel codice blow

//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

L'OP ha chiesto "Sto cercando di capire come impostare uno stato iniziale per un negozio in redux." – ctrlplusb

13

È possibile impostare lo stato iniziale del riduttore (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 
}) 
Problemi correlati