繁体   English   中英

使用 useEffect 和 useParams React Hook 时如何修复缺少的依赖警告

[英]How to fix missing dependency warning when using useEffect and useParams React Hook

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 做一个项目,任何提示都会真正帮助我 **

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])

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

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

  }, [id])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM