Redux todo列表先进

时间:2016-03-09 16:05:01

标签: reactjs redux

我正在使用redux做一个待办事项列表,我想为每个待办事项添加子待办事项列表,但我不明白为什么我的减速机线路无效(见上文) 你能帮帮我吗?

import { combineReducers } from 'redux'
import { ADD_TODO, TOGGLE_TODO, ADD_SUB_TODO} from '../constants/ActionTypes'
import _ from 'lodash'

const initialState = {
    todos : []
}

export function todo(state, action) {
    switch (action.type) {
        case  ADD_TODO:
            return {
                id: action.id,
                text: action.text,
                completed: false
            };
        default:
            return state;
    }
}


export function allTodo (state = initialState, action) {
    switch (action.type) {
        case  ADD_TODO:
            return {
                ...state,
                todos: [
                    ...state.todos,
                    {
                        id: action.id,
                        text: action.text,
                        completed: false,
                        subtodo:[]
                    }
                ]
            };
        case ADD_SUB_TODO:
            console.log("REDUCER")
            console.log(...state.todos)
            return {
                ...state,
        // THIS LINE DOES'NT WORK :
                ...state.todos[0].subtodo: [ ...state.todos[0].subtodo, {
                    id: action.id,
                    text: action.text
                }]
            };
        default:
            return state;
    }
};

export default combineReducers({
    allTodo
})

此行不起作用:

...state.todos[0].subtodo: [ ...state.todos[0].subtodo, {
                        id: action.id,
                        text: action.text
                    }]

这是我的子todo对象:

{
 id: action.id,
 text: action.text
}

2 个答案:

答案 0 :(得分:2)

假设action.parent包含父todo的索引,请尝试此操作。

        case ADD_SUB_TODO:
            let subtodo = {id: action.id, text: action.text}
            let subtodos = [...state.todos[action.parent].subtodo, subtodo]
            let todo = _.assign({}, state.todos[action.parent], {subtodo: subtodos})
            return _.assign({}, state, {todos: [...state.todos, todo]})

如果你想以你的问题的方式尝试一下,

        case ADD_SUB_TODO:
            let subtodo = {id: action.id, text: action.text}
            let todo = _.assign({}. state.todos[0], {subtodo: [subtodo]})
            return _.assign({}, state, {todos: [...state.todos, todo]})

答案 1 :(得分:1)

感谢Mad Wombat,这是最终的代码:

case ADD_SUB_TODO:

                let subtodo = {id: action.id, text: action.text}
                let subtodoList = _.concat(...state.todos[action.parentId].subtodo, subtodo)
                let todo = _.assign({}, state.todos[action.parentId], {subtodo: subtodoList})

                return {
                    ...state,
                    ...state.todos[action.parentId] = todo,
                    todos: [
                        ...state.todos
                    ]
                };