如何修复使用useEffect和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做一个项目,任何技巧都会真正帮助我**

这是关于react钩子中的COMPONENTDDUPDATE的,您可以在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])

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

最新更新