首页 > 解决方案 > ESLinter 询问 useEffect 一个 dep

问题描述

我有这个useEffect:

useEffect(() => {
  if (allValidated) {
    setState({
      ...state,
      buttonDisabled: false
    });
  } else {
    setState({
      ...state,
      buttonDisabled: true
    });
  }
}, [allValidated, validation]); // HERE is the warning:

React Hook useEffect has a missing dependency: 'state'. Either include it or remove the dependency array. You can also do a functional update 'setState(s => ...)' if you only need 'state' in the 'setState' call

但是,如果我将state组件添加到 deps 数组中,则会进入一个循环。

state定义为:

const [state, setState] = useState(defaultState);

这个对象在哪里defaultState,可以在不同的部分进行更新:

const defaultState = {
  amplifyError: false,
  buttonDisabled: true,
  errors: defaultError,
  password: '',
  show: false,
  username: '',
  validation: defaultValidation
};

我不想使用 a@ts-ignore因为我认为它可以被解决,而不是被忽略。有什么提示吗?

标签: use-effecttypescript-eslint

解决方案


如警告中所述,您还可以进行功能更新setState(s => ...)。例如,您的第一个 setState 如下所示:

setState(s => {
    ...s,
    buttonDisabled: false
});

等等第二个!


推荐阅读