首页 > 解决方案 > 在使用 React 钩子验证新状态时修改上游状态

问题描述

我正在尝试使用与此类似的 React 钩子:

function MyComponent({ setError }) {
  const [total, setTotal] = useState('');
  // ...
  useEffect(() => {
    setTotal(oldTotal => {
      const newTotal = oldTotal + inputValue;
      // some validation step
      if (newTotal.length % 2 !== 0) {
        setError(`${inputValue} was wrong`);
        return oldTotal;
      }

      return newTotal;
    });

  }, [inputValue, setError]); // I don't want this to re-evaluate when `total` changes.

  // ...
}

但是,setError触发另一个useState回调会触发另一个重新渲染,并且 React 不喜欢在状态转换期间重新渲染。

我应该如何构造这段代码,以便setError在它应该被调用时被调用?

标签: javascriptreactjsreact-hooks

解决方案


推荐阅读