【问题标题】:React useEffect gets error - Missing Dependency [duplicate]React useEffect 出错 - 缺少依赖项 [重复]
【发布时间】:2020-03-04 19:46:39
【问题描述】:

我尝试使用 useEffect 但它得到的错误如下所示,

React Hook useEffect has a missing dependency: 'data'. Either include it or remove the dependency array

这是我的组件,

let id = props.location.pathname.split("--")[1];
let str = props.location.pathname.split("--")[0].substr(1);
const data = {id: id, link: str}

const [title, setTitle] = useState("")

useEffect(() => {
    setTitle("...") // Yükleniyor.
    async function getTitle() {             
        axios.post('/api/data/entry/get', data)
        .then(res => {
        setTitle(res.data.title)
        // TODO: Catch ekle.
        })
    }
    getTitle()
}, [props])

【问题讨论】:

  • 编写代码的最佳方式是将 id 和 str 作为 deps 传递给 useEffect 并在 useEffect 回调中形成数据对象

标签: reactjs react-hooks use-effect


【解决方案1】:

您必须在依赖数组中包含“数据”。这是因为您的钩子在其回调中使用它。

这样,每次更改依赖数组中的变量之一时都会调用挂钩。

我注意到“数据”对象使用组件属性中的值。你可能会说“好吧,那我为什么要同时包含道具和数据呢?”好吧,在定义依赖数组时,您需要尽可能细化。让它依赖于道具太笼统了。在你的情况下,你应该让它只依赖于“数据”

编辑

我错过了这样一个事实,即如果您要添加 data 作为依赖项,那么每次重新渲染都会触发挂钩。那是因为data 基本上是每个渲染的新对象。您可以将data 的成员分成变量并将它们用作依赖项:

您的组件现在看起来像这样:

const id = props.location.pathname.split("--")[1];
const str = props.location.pathname.split("--")[0].substr(1);

const data = useRef({id: id, link: str});

const [title, setTitle] = useState("")

useEffect(() => { /* ... */ }, [id, str]);

请注意,我没有测试过代码。请看看这是否有效。

【讨论】:

  • 谢谢。但是,如果我不向依赖项添加道具,则 useEffect 不会在每次路由更改时都起作用。我试过了。当我将数据添加到依赖项时,它会每秒自动将数据发布到服务器。
  • @MehmetDemiray 这是因为data 是每次您的组件渲染时的新对象。不如使用props.location 作为依赖项?
【解决方案2】:

您必须将数据添加到您的依赖项列表中,如下所示

let id = props.location.pathname.split("--")[1];
let str = props.location.pathname.split("--")[0].substr(1);
const data = {id: id, link: str}

const [title, setTitle] = useState("")

useEffect(() => {
    setTitle("...") // Yükleniyor.
    const getTitle = async () => {
      const res = await 
        axios.post('/api/data/entry/get', data)
        setTitle(res.data.title)
        // TODO: Catch ekle.
        };
    getTitle()
}, [props])

【讨论】:

  • 当我将数据添加到依赖项时,它会每秒自动将数据发布到服务器。
猜你喜欢
  • 2021-10-16
  • 2021-08-19
  • 2021-02-23
  • 1970-01-01
  • 2020-12-13
  • 2019-10-24
  • 2020-10-26
  • 2021-04-26
相关资源
最近更新 更多