React useEffect警告以放置缺少的依赖项.但是依赖值在钩子中发生了变化



当步长的值发生变化时,我想更改formStepTouched的值,所以我使用useEffect。但useEffect发出了一个警告,即它缺少对formStepTouched的依赖。由于这是一个正在变化的值,将其放入依赖数组将导致无限调用。

 const [step, setStep] = useState(0);
 const [formStepTouched, setFormStepTouched] = useState(
    Array(childrenArray.length)
      .fill(false)
      .map((_, idx) => idx === 0)
 )
 useEffect(() => {
    const newFormStepTouched = [...formStepTouched];
    newFormStepTouched[step] = true;
    setFormStepTouched(newFormStepTouched);
  }, [step]);

请参阅下面的codesandbox链接:https://codesandbox.io/s/brave-gould-ymjt0?file=/src/App.js

正如您所看到的,演示工作非常完美,但会显示一条错误消息。如果添加dependency,useEffect将被无限调用。

如何清除错误消息。

您可以将回调传递给状态设置器:

const { useEffect, useState } = React;
const App = () => {
  const [step, setStep] = useState(0);
  const [formStepTouched, setFormStepTouched] = useState(
    Array(5)
      .fill(false)
      .map((_, idx) => idx === 0)
  );
  useEffect(() => {
    //pass a callback to state setter
    setFormStepTouched((formStepTouched) => {
      if (formStepTouched[step] === true) {
        //nothing to change
        return formStepTouched;
      }
      return formStepTouched.map((s, i) =>
        i === step ? true : s
      );
    });
  }, [step]);
  return (
    <div>
      <button onClick={() => setStep(step + 1)}>
        nex step
      </button>
      <div>
        <pre>
          {JSON.stringify(formStepTouched, undefined, 2)}
        </pre>
      </div>
    </div>
  );
};
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

   useEffect(() => {
    setFormStepTouched(prevState =>  {
      const newFormStepTouched = [...prevState]
      newFormStepTouched[step] = true
      return newFormStepTouched
    });
  }, [step]);

linter告诉你,有一个可能会改变的外部依赖,你可以在这里阅读更多

相关内容

  • 没有找到相关文章

最新更新