如何更新减速机商店

时间:2018-10-24 11:33:10

标签: javascript arrays reactjs object react-redux

我有这样的商店

export const list = [
    {
        id: 0,
        tableName: 'example',
        tasks: [
            {
                task_id: 0, 
                task_short: 'lorem',
                task_full: 'lorem ipsum lorem ipsum lorem ipsum',
                time_created: '10:20',
                time_created: null, 
            },
            {
                task_id: 1, 
                task_short: 'andsf',
                task_full: 'lorem ipsum tes tes est',
                time_created: '13:20',
                time_created: null, 
            }
        ]
    }
]

如果我更改 tableName 或使用此reducer添加新的

import { list } from './list'

export default (state = list, action) => {
    const { type, payload } = action
    switch(type) {
        case 'ADD_TABLE':
            return [...state, payload]
        case 'DELL_TABLE':
            return  state.filter( ( tabl ) => tabl.id != payload )   
        case 'CHANGE_TITLE':
            let basket = state.map( bas => bas.id == payload.id ? bas.tableName = payload.val : bas )
            return [...state]
        case 'ADD_TASK':
            const newer = state.map( tas =>  tas.id == payload.id ? tas.tasks.push(payload.t) : tas)
            return [...state]

        default:
            return state
    }
}

所有作品!

但是如果我在 tasks 中推送新任务,则会在控制台中存储它,但不渲染。

要使其呈现,我必须更改 tableName ,然后将其全部显示

我想这里的问题

case 'ADD_TASK':
                const newer = state.map( tas =>  tas.id == payload.id ? tas.tasks.push(payload.t) : tas)
                return [...state]

这是演示 http://kanban.antus.pro/

并回购enter link description here

1 个答案:

答案 0 :(得分:1)

Array.push()更改初始数组,这是redux https://redux.js.org/faq/immutabledata中的反模式

您应该更改此行

const newer = state.map( tas => tas.id == payload.id ? tas.tasks.push(payload.t) : tas)

在此

const newer = state.map( tas => tas.id == payload.id ? [...tas.tasks, payload.t] : tas)

因此您不会突变初始tas.tasks数组

尝试不要在化简器https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype#Mutator_methods中使用此列表中的方法