代码段:
updateSelectedAreaColor: (state, payload) => {
state.selectedArea = { ...state.selectedArea, color: payload };
},
我正在使用有效负载更新对象 state.selectedArea 的属性颜色。与其对要更新的属性进行硬编码,我想通过我的有效载荷设置属性。
例如:
updateSelectedAreaColor: (state, payload) => {
state.selectedArea = { ...state.selectedArea, payload.target: payload.value };
},
但是,此代码将引发错误。有人知道我如何设置要通过有效负载更新的值吗?
答案 0 :(得分:-1)
动态属性放在括号中
updateSelectedAreaColor: (state, payload) => {
state.selectedArea = { ...state.selectedArea, [payload.target]: payload.value };
},
但是我更希望:
updateSelectedAreaColor: (state, payload) => {
state.selectedArea = { ...state.selectedArea, ...payload};
},
这样,您可以轻松地同时更改多个道具:
updateSelectedAreaColor(this.state, { color: "green", backgroundColor: "red" });