javascript - 通过 React 的 useState 钩子设置状态时删除键的最佳或最有效的方法是什么?
问题描述
我们的项目正在拥抱新的功能性 React 组件并大量使用各种钩子,包括useState
.
与 React 类的setState()
方法不同,useState() 返回的 setter 完全替换状态而不是合并。
当状态是地图并且我需要删除一个键时,我克隆现有状态,删除键,然后设置新状态(如下所示)
[errors, setErrors] = useState({})
...
const onChange = (id, validate) => {
const result = validate(val);
if (!result.valid) {
setErrors({
...errors,
[fieldId]: result.message
})
}
else {
const newErrors = {...errors};
delete newErrors[id];
setErrors(newErrors);
}
有没有更好的选择(更好的效率和/或标准)?
解决方案
If you need more control when setting a state via hooks, look at the useReducer
hook.
This hook behaves like a reducer in redux - a function that receives the current state, and an action, and transforms the current state according to the action to create a new state.
Example (not tested):
const reducer = (state, { type, payload }) => {
switch(type) {
case 'addError':
return { ...state, ...payload };
case 'removeError':
const { [payload.id]: _, ...newState };
return newState;
default:
return state;
}
};
const [state, dispatch] = useReducer(reducer, {});
...
const onChange = (id, validate) => {
const result = validate(val);
if (!result.valid) {
dispatch({ type: 'addError', payload: { [id]: result.message }})
}
else {
dispatch({ type: 'removeError', payload: id })
}
推荐阅读
- python - 替换 Numpy 图像中的像素值
- java - 将映射键从集合转换为双精度 - java
- java - 限制缓冲区读取器以防止 DoS 攻击
- c# - 仅查看 Model OnPropertyChanged 上的更新,而不是 ViewModel OnPropertyChanged 上的更新
- cryptography - 两方之间文件的理论签名
- c# - 从另一个类访问文本框变量
- mysql - 同一 MySQL 查询的不同结果
- python - 是否可以使用 Python 将 HTML 页面保存为 PDF?
- html - 如何在图像顶部创建弯曲的背景
- regex - 邮递员:如何从 html 响应中提取值并将其传递给邮递员中的下一个请求