簡體   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