【问题标题】:How to fix missing dependency warning when using useEffect and useParams React Hook使用 useEffect 和 useParams React Hook 时如何修复缺少的依赖警告
【发布时间】:2022-08-14 01:17:38
【问题描述】:
import React from \'react\'
import { useParams, useEffect, useState } from \'react\'
import axios from \"axios\";
import \'./App.css\';
const Todo = () => {
  const [todoDetails, setTodoDetails] = useState();
  const { id } = useParams();
  useEffect(() => {
// I wanted to fetch the data for the specific id from the jsonPlaceholder url to practice 

    axios
      .get(`https://jsonplaceholder.typicode.com/todos/${id}`)
      .then((res) => {
        const responseTodo = res.data;
        setTodoDetails(responseTodo);
      });

  }, [])//the console said the error is here but i don\'t know what to do 
// the error is \"  Line 17:6:  React Hook useEffect has a missing dependency: \'id\'. Either include it or remove the dependency array  react-hooks/exhaustive-deps\"
  const { id: todoId, userId, title, completed } = todoDetails || {}
  return (
    <div>{`this is the todoes componets and the id is  ${todoId} , ${userId}, ${title}, ${completed}`}</div>
  )
}
export default Todo;

**我是开发人员世界的新手,我刚开始学习 JS。我被要求使用 React js 做一个项目,任何提示都会真正帮助我**

  • }, []) => }, [id])(请先google错误信息)

标签: javascript reactjs react-hooks dependencies


【解决方案1】:

它是关于 react hooks 中的 COMPONENTDIDUPDATE 的,您可以在 https://reactjs.org/docs/state-and-lifecycle.html 中了解更多关于状态和生命周期概念的信息。您的代码必须是这样的:

useEffect(() => {
    axios
      .get(`https://jsonplaceholder.typicode.com/todos/${id}`)
      .then((res) => {
        const responseTodo = res.data;
        setTodoDetails(responseTodo);
      });

  }, [id])

【讨论】:

  • 警告消失了,但它不会显示任何内容id } = useParams();"我只需要从“react-router-dom”导入 { useParams };
【解决方案2】:

useEffect 使用依赖数组作为第二个参数来观察变化,所以基本上如果你将依赖数组留空,useEffect 只会在组件挂载时运行一次。

如果您在依赖数组中添加一个或更多属性,它将在每次这些值更改时运行。

在这种情况下,您的 useEffect 使用 id 进行 api 调用,但我只会运行一次,警告会告诉您,所以如果 id 道具发生变化,useEffect 将不会运行

如果您希望每次 id 更改时都运行 useEffect,请添加以下内容:

useEffect(() => {
  // Rest of the code.  
  // Adding the id here will make this effect to run everytime the id changes.
  }, [id])

【讨论】:

  • 警告消失了,但它不会显示任何内容id } = useParams();"我只需要从“react-router-dom”导入 { useParams };
猜你喜欢
  • 2019-10-16
  • 2021-12-07
  • 1970-01-01
  • 2020-11-21
相关资源
最近更新 更多