2016-06-14 40 views
22

Tôi đang cố gắng tìm ra cách đặt trạng thái ban đầu cho một cửa hàng trong quá trình chuyển đổi. Tôi đang sử dụng https://github.com/reactjs/redux/blob/master/examples/todos-with-undo/reducers/index.js làm ví dụ. Tôi đã cố gắng sửa đổi mã như vậy mà các todos đã có một giá trị khởi tạo.cách đặt trạng thái ban đầu trong redux

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

sau khi doc: http://redux.js.org/docs/api/createStore.html

nhưng nó không làm việc, và tôi không hoàn toàn chắc chắn lý do tại sao.

Trả lời

41

Nó cần phải được đối số thứ hai để createStore:

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

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

const store = createStore(
    rootReducer, 
    initialState 
); 
-3
  1. bạn có lỗi cú pháp
  2. chỉ cần đặt trạng thái ban đầu trong sáng tạo hành động và gọi nó là trên componentWillMount
  3. làm giảm tốc: xuất khẩu hàm mặc định() {return todo: ['read', 'eat', 'sleep'];} 4: để làm cho bạn rõ ràng es6 được sử dụng trong đoạn mã

//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 hỏi "Tôi đang cố gắng tìm hiểu cách đặt trạng thái ban đầu cho cửa hàng trong quá trình chuyển đổi." – ctrlplusb

13

Bạn có thể thiết lập trạng thái ban đầu trong giảm tốc (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 
}) 
Các vấn đề liên quan