首页 > 解决方案 > 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

我该如何改进呢?

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

标签: javascriptreactjsstateeslintuse-effect

解决方案


推荐阅读