如何从redux reducer返回不可变数据?

问题描述 投票:0回答:1

对于学习和测试项目,我试图从reducer返回不可变的redux数据,因为组件的安全数据。这是我的reducer代码:

function itemsReducer(state = [], action) {
    switch(action.type) {
        case 'ITEMS':
            return [...action.data]
        default:
            return state
    }
}

这是我的循环代码:

<ul>
    {
        this.props.items.map((item) => (
            <li>{item.name.first} {item.name.last}</li>
        ))
    }
</ul>

现在每件事情都正常,但在使用此方法更改道具后:

change() {
    this.props.items[0] = 'empty'
}

再次加载项目后,我有这个错误:

TypeError: Cannot read property 'first' of undefined

显然,这些项目没有在我的reducer中使用扩展语法进行复制,并且所有更改都会覆盖它。在所有索引执行数据加载操作后,#0为'空'

谢谢

javascript reactjs redux react-redux immutability
1个回答
4
投票

您不应该直接在组件中改变道具,而是调度在reducer中更新结果的操作

change() {
    this.props.updateItem({first: 'empty'}, 0);
}

和行动创造者会

const updateItem = (item, index) => {
   return {type: 'UPDATE_ITEM', item, index}
}

和减速机

function itemsReducer(state = [], action) {
    switch(action.type) {
        case 'ITEMS':
            return [...action.data]
        case 'UPDATE_ITEM': 
            return [...state.slice(0, action.index), {...state[index], ...action.item}, ...state.slice(index+1)];
        default:
            return state
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.