React-useEffect-如何初始化组件状态-缺少依赖项警告

问题描述

我正在建立一个表单,其中一步是选择卡片。我有两个useEffect函数

一个等效于ComponentDidMount,它允许我选择以前选择的卡(在表单步骤之间导航时很有用)。数据从上级组件作为道具接收。

    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

我该如何改善?

处理状态初始化的最佳实践是什么?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)