2016-06-14 10 views
22

Próbuję dowiedzieć się, jak ustawić stan początkowy dla sklepu w redux. Używam przykładu https://github.com/reactjs/redux/blob/master/examples/todos-with-undo/reducers/index.js. Próbowałem zmodyfikować kod tak, aby todos miał zainicjowaną wartość.jak ustawić stan początkowy w redux

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

po Doc: http://redux.js.org/docs/api/createStore.html

ale to nie działa, i nie jestem pewien, dlaczego.

Odpowiedz

41

Musi być drugi argument do createStore:

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

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

const store = createStore(
    rootReducer, 
    initialState 
); 
-3
  1. masz błąd składni
  2. wystarczy umieścić stan początkowy w twórca akcji i wezwanie go na componentWillMount
  3. złożyć reduktor: eksport domyślna funkcja() {return todo: ["czytaj", "zjedz", "śpij"];} 4: abyś wyczyścił es6 jest używany w ciosie kodu

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

Program OP zapytał "Próbuję dowiedzieć się, jak ustawić stan początkowy dla sklepu w redux." – ctrlplusb

13

Można ustawić stan początkowy w reduktorze (ów).

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 
}) 
Powiązane problemy