如何在 REDUX 状态下更新数组中的元素为
var initialState = {
DataArray :[],
isSelected : flase,
}
前任:
var DataArray = [
{place:NY ,Bool:true},
{place:Boston ,Bool:true}
]
更新为
var DataArray =[
{place:NY ,Bool:false},
{place:Boston ,Bool:true},
]
检查我下面的代码。愿 b 它会帮助你。在化简器中使用此代码,要在其中更新数组中的数据。
return { ...state,
stateArray: state.stateArray.map(data => {
if (data.place === action.payload.data.place) {
return action.payload.data;
}
else {
return {place:data.place,count:data.count,selected:false};
}
}
)
}
假设有效负载中有要更新的对象,并且操作类型为UPDATE_ARRAY
case 'UPDATE_ARRAY':
let data = [...state.DataArray],
index = data.findIndex(r => r.place === action.payload.place) //finding which index should get the udpate
if(index > -1) //
{
data[index] = action.payload
return {...state,DataArray: data}
// ES5 --> return Object.assign({},state,DataArray: data)
}
else return state