首页 > 解决方案 > 通过 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);
  }

有没有更好的选择(更好的效率和/或标准)?

标签: javascriptreactjsecmascript-6react-hooks

解决方案


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 })
  }

推荐阅读