ESlinter asking on useEffect a 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添加到深度数组中,则组件进入循环。

state定义为:

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

其中defaultState为该对象,可在不同部分更新:

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

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

正如警告中所说,您还可以对setState(s => ...)进行功能更新。例如,你的第一个setState看起来像这样:

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

,依此类推!

最新更新