javascript - 如何简化这个react-redux reducer 状态变化

标签 javascript reactjs react-redux

我有一个 reducer ,它的数据属性是对象数组。也就是说,基本上:

state.data[0] = {id: 1,name: 'joe',tired=true}
state.data[1] = {id: 2,name: 'linda',tired=false}
etc.

我发现在我的 reducer 中,如果我想让琳达不累,我必须深入挖掘以迫使 react “不同”引擎识别发生了状态变化。正如您通过下面的代码所看到的,我实际上已经创建了对所有内容的新引用。

有没有更简单的方法来做到这一点?我希望我能理解 diff 如何更好地工作,以便当我将给定行的属性 Tired 设置为 true 时,我的对象会被渲染。感觉就像我正在击败一切。

        const idToUpdate = 2;
        newState = Object.assign({}, state);
        let newData = [];
        newState.data.map(function(rec){
            if (rec.id === idToUpdate) {
                rec.interestLevel = 998;
                newData.push(rec);
            } else {
                newData.push(rec);
            }
        });
        newState.data = newData;

最佳答案

如果你知道要更新的 id 并且假设你有一个对象数组,那么你可以执行类似的操作

const {data} = this.state;
const arr = data;
const Linda = arr.filter(item => item.id === idToUpdate)
var TiredLinda = Linda.map(item => return {id:item.id, name:item.name, tired:true}
//Now remove Linda from the original array
arr.filter(item => item.id !== idToUpdate)
//Now we will push the updated Linda to arr to replace the one we removed
arr.push(TiredLinda);

现在您想要设置数据的状态

this.setState({data:arr});

关于javascript - 如何简化这个react-redux reducer 状态变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49268170/

相关文章:

javascript - 在react中刷新传单 map

javascript - 使用对象而不是字符串进行 "to"时,React-router 重定向错误

javascript - 十六进制到 base 62 转换以缩短 URL

javascript - 使用 async/await 从 firebase 数据库顺序检索数据不起作用

javascript - 使用 Redux/React 移动数组中的项目

javascript - ajax 调用后选项卡不工作

reactjs - Firebase 云消息传递在窗口焦点之外时不显示通知

javascript - 使用 AWS 的 getObject 在浏览器中显示图像

javascript - 从深层嵌套组件访问 redux 调度

node.js - React-Redux大型自定义数据表