Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 根据条件更新状态并添加新属性,最后检索更新的状态_Reactjs_Ecmascript 6_React Redux - Fatal编程技术网

Reactjs 根据条件更新状态并添加新属性,最后检索更新的状态

Reactjs 根据条件更新状态并添加新属性,最后检索更新的状态,reactjs,ecmascript-6,react-redux,Reactjs,Ecmascript 6,React Redux,每当单击按钮时,我都会传递id,因此我的状态是有三个对象 state = items:[{ id:1, material: 'iron' }, id:2, material: 'steel' }, id:3, material: 'coal' }] //reducer.js case actionTypes.UpdateMaterialToShow: return { ...state, items: state.items.map(obj => {

每当单击按钮时,我都会传递id,因此我的状态是有三个对象

state = items:[{
 id:1,
 material: 'iron'
},
 id:2,
 material: 'steel'
},
 id:3,
 material: 'coal'
}]


//reducer.js

case actionTypes.UpdateMaterialToShow:
  return {
   ...state,
   items: state.items.map(obj => {
    if(obj.id === action.payload.id){
      obj.['show'] = action.payload.status
    }
  }) 
}
因此,每当调用该方法时,我都会传递id和状态,因此我需要将属性添加到state.items

如果单击的按钮是熨斗,则预期输出为

state = items:[{
 id:1,
 material: 'iron',
 status: true
},
 id:2,
 material: 'steel'
},
 id:3,
 material: 'coal'
}]
创建新数组时,如何在不改变状态的情况下返回如上所示的更新状态。只要对象的
id
等于有效负载的
id
,您就需要基于旧对象创建一个新对象,并具有更新的属性

可以使用或(如示例所示)创建新对象:

case actionTypes.UpdateMaterialToShow:
  return {
    ...state,
    items: state.items.map(obj => {
      if (obj.id === action.payload.id) {
        return { ...obj,
          status: action.payload.status
        };
      }

      return obj;
    })
  }
你可以用

return {
  ...state,
  items: state
    .items
    .map(obj => {
      if (obj.id === action.payload.id) {
        return {
          ...obj,
          status: action.payload.status
        }
      } else {
        return obj;
      }
    })
}