【问题标题】:change value of property in state reducer redux更改 state reducer redux 中的属性值
【发布时间】:2017-04-13 12:49:31
【问题描述】:

我有一个减速器,它的状态是一个对象数组。

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

我的 reducer 的相关部分如下所示。

action.id这里是1

case 'TOGGLE_VIEW':

    return state.map(item => {

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

            item.visible = !item.visible;

        }

    });

上面的代码返回状态为[null, null]

谁能解释我如何根据传入的 id 更改状态中的属性值?

【问题讨论】:

  • .map 中缺少return
  • 抱歉,更新了!
  • 一些错字:name 'peter' gorgot :{ id: 2, name: 'alan', visible: false ] 忘记了 } Rajesh 对,你不会在地图中返回任何内容。

标签: javascript reactjs redux


【解决方案1】:

跟进 naortor 的回答,因为 redux 状态应该是不可变的,你应该这样做:

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

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

    return item

  });

【讨论】:

    【解决方案2】:

    您在地图回调函数中缺少返回

    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.
    
    });
    

    【讨论】:

      猜你喜欢
      • 2020-05-31
      • 2016-01-29
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      • 2016-06-10
      • 2022-01-05
      • 2021-02-09
      • 2018-09-06
      相关资源
      最近更新 更多