【问题标题】:ESlinter asking on useEffect a depESLinter 询问 useEffect 一个 dep
【发布时间】:2021-02-18 21:42:00
【问题描述】:

我有这个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
};

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

【问题讨论】:

    标签: use-effect typescript-eslint


    【解决方案1】:

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

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

    第二个以此类推!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-05
      • 2023-02-07
      • 1970-01-01
      • 2021-12-22
      • 2020-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多