javascript - React - useEffect - 如何初始化组件状态 - 缺少依赖项警告
问题描述
我正在构建一个表单,其中一个步骤是卡片选择。我有两个 useEffect 函数。
第一个等效于 ComponentDidMount,它允许我选择以前选择的卡片(在表单步骤之间导航时很有用)。数据作为 props 从父组件接收。
useEffect(() => {
/* Allow to display previously selected image (when navigating between form steps)
Run each time the component is rendered */
setSelectedImage({ id: props.values.image_id });
}, []);
第二个允许我在选择卡片时使用当前选择的卡片信息更新父母的状态。
useEffect(() => {
/* Allow to store currently selected image parameters in parent's state
Run each time selectedImage changes */
props.handleCardChange(selectedImage.params);
console.log(selectedImage.params);
}, [selectedImage]);
它正在工作,但我有这些警告:
Line 118:5: React Hook useEffect has a missing dependency: 'props.values.image_id'. Either include it or remove the dependency array. If 'setSelectedImage' needs the current value of 'props.values.image_id', you can also switch to useReducer instead of useState and read 'props.values.image_id' in the reducer react-hooks/exhaustive-deps
Line 125:5: React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array. However, 'props' will change when *any* prop changes, so the preferred fix is to destructure the 'props' object outside of the useEffect call and refer to those specific props inside useEffect react-hooks/exhaustive-deps
我该如何改进呢?
处理状态初始化时的最佳实践是什么?
解决方案
推荐阅读
- r - 强制 r 在变异后不舍入结果
- python - 为什么我的 pygame rect 敌人在被杀死后会减速?
- javascript - 在 Vue 3 中访问和修改 slot 的元素
- swift - 如何摆脱 SwiftUI TabView 上的错误“传递给不带参数的调用的参数”
- javascript - 我的钩子没有打开和关闭我的模态
- python - 如何使用 find_peak 函数 Python 的值
- node.js - async/await 无法与 fs.writeFile 一起正常工作
- python - 如何在 matplotlib 上将 2 个子图图形组合成 1 个?
- swiftui - navigationBarHidden 结合内联显示方式导致跳转
- elasticsearch - 是否可以对 Solr/Elasticsearch 索引中的文档进行部分/选择性搜索?