reactjs - 如何仅更新 1 个字段而不覆盖 React Hooks 上的嵌套对象上的其他字段使用 Reducer?
问题描述
我开始学习 React + hooks。我现在正在使用 useReducer。但是我在更新我的 useReducer 状态时遇到了问题。每次我想更新对象状态的 1 个字段时,所有其他字段都会被删除。
我的解决方案是将所有现有值传递给它们,即使我只需要更新 1 个字段。有没有更有效的方法来做到这一点?
这是我的解决方案:
const initialState = {
filter: {
text: "Filter",
list: [],
isActive: false,
message: "",
},
apiList: []
};
const reducer = (state, action) => {
switch (action.type) {
case "SET_FILTER_LIST":
return {
...state,
filter: { ...state.filter,
list: action.payload.list,
isActive: action.payload.isActive,
message: action.payload.message,
text: action.payload.text,
}
};
default:
return state;
}
};
//BELOW - I just want to pass the e.target.textContent to text field. To avoid deleting the other fields. I re-pass all the existing value so it wont get deleted.
const onSelect = e => {
let filter = e.target.textContent;
dispatch({
type: 'SET_FILTER_LIST',
payload: {
list: state.filter.list,
text: filter,
message: state.filter.message,
isActive: state.filter.isActive
}
});
};
解决方案
您可以使用以下代码:
return {
...state,
filter: {
...state.filter,
...action.payload,
}
};
推荐阅读
- python - TypeError:'int'对象不可迭代如何解析python dict
- python - 具有多个输入参数和多个输出参数的神经网络
- mysql - Docker:多个mysql容器
- pdf - PDF 文件元数据的批处理编辑器
- logging - 如何将日志聚合到 splunk 中的持久表?
- html - Selenium 如何点击 50% 在屏幕上和 50% 不在屏幕上的元素?
- google-sheets - 在 Google 表格中,如何计算添加的项目数量
- java - RS232 - JSSC 2.8.0 串行端口阅读器 - 不明确的阅读
- javascript - 将yaml字符串转换为nodejs模块中的函数引用(不调用函数)
- python - 从多个连续动作中选择 1 个动作