use-effect - 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
因为我认为它可以被解决,而不是被忽略。有什么提示吗?
解决方案
如警告中所述,您还可以进行功能更新setState(s => ...)
。例如,您的第一个 setState 如下所示:
setState(s => {
...s,
buttonDisabled: false
});
等等第二个!
推荐阅读
- reactjs - antd onChange 每次击键都会触发 3 次
- c# - 在同步融合数据网格中编辑 GridNumericColumn 时丢失小数点
- java - 为什么没有从网站上的跨度文件中解析值?
- java - Xmx 内存分配给容器时出错
- git - 壁球提交选项在 Visual Studio 社区中被禁用
- azure - Azure 负载均衡器 - 使用 ARM 模板将现有 VM 添加到 Azure 负载均衡器
- graphql - 为随机 id 生成模式
- firebase - 颤动中按索引引用的Firestore文档
- node.js - 无法在 Mocha 测试中使用创建的 Sequelize 模型
- flutter - 如何在颤动中为谷歌图表添加工具提示?