reactjs [eslint] React Hook UseEffect中的警告缺少依赖项

whlutmcx  于 2023-03-22  发布在  React
关注(0)|答案(1)|浏览(196)

这是密码

import axios from 'axios';
import React, { useEffect, useState } from 'react';
import Header from './../components/Header';

const SingleProduct = ({ match }) => {
  const [product, setProduct] = useState({});

  useEffect(() => {
    const fetchproduct = async () => {
      const { data } = await axios.get(`/api/products/${match.params.id}`);
      setProduct(data);
    };
    fetchproduct();
  }, []);

我一直收到这样的警告

WARNING in [eslint]
src\screens\SingleProduct.js
  Line 14:6:  React Hook useEffect has a missing dependency: 'match.params.id'. Either include it or 
remove the dependency array  react-hooks/exhaustive-deps

我是初学者,所以我不知道怎么修

g2ieeal7

g2ieeal71#

你的效果取决于match.params.id,它不存在于依赖数组中,添加它将解决这个问题。

useEffect(() => {
    const fetchproduct = async () => {
      const { data } = await axios.get(`/api/products/${match.params.id}`);
      setProduct(data);
    };
    fetchproduct();
  }, [match.params.id]); // ADD HERE

相关问题