简体   繁体   English

更改状态减少器redux中的属性值

[英]change value of property in state reducer redux

I have a reducer that's state is an array of objects. 我有一个化简器,其状态是对象数组。

state = [{
      id: 1,
      name: 'peter',
      visible: false
    },
    {
      id: 2,
      name: 'alan',
      visible: false
    ];

The relevant part of my reducer looks like this. 我的减速器的相关部分看起来像这样。

action.id here is 1 action.id这里是1

case 'TOGGLE_VIEW':

    return state.map(item => {

        if(item.id === action.id) {

            item.visible = !item.visible;

        }

    });

The code above returns state to be [null, null] 上面的代码返回状态为[null, null]

Can anyone explain how I can change the value of property in the state based on an id passed in? 谁能解释我如何根据传入的ID更改状态中的property值?

Following up on naortor's answer, since redux state should be immutable, you should do this: 跟进naortor的回答,由于redux状态应该是不变的,因此您应该这样做:

case 'TOGGLE_VIEW':
  return state.map(item => {

    if (item.id === action.id) {
      return {
        ...item,
        visible: !item.visible,
      }
    }

    return item

  });

You are missing a return inside the map callback function 您在地图回调函数中缺少返回值

case 'TOGGLE_VIEW':

return state.map(item => {

    if(item.id === action.id) {

        item.visible = !item.visible;

    }

    return item // you need a return inside your map callback function.

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM