简体   繁体   English

React Hook useEffect 缺少依赖项:'match.params.id'

[英]React Hook useEffect has a missing dependency: 'match.params.id'

React Hook useEffect has a missing dependency: 'match.params.id'. Either includes it or remove the dependency array, this is the error I continuously get while using useEffect


  useEffect(() => {
    const fetchData = async () => {
      let data = await getPost(match.params.id);
      console.log(data);
      setPost(data);
    };
    fetchData();
  }, []);

this will work, need to include 'match.params.id' in useEffect dependency array,这会起作用,需要在 useEffect 依赖数组中包含“match.params.id”,

useEffect(() => {
    const fetchData = async () => {
      let data = await getPost(match.params.id);
      console.log(data);
      setPost(data);
    };
    fetchData();
  }, [match.params.id]);

You need to update your dependency array in useEffect hook like below.您需要像下面这样在 useEffect 挂钩中更新依赖项数组。

useEffect(() => {
    const fetchData = async () => {
      let data = await getPost(match.params.id);
      console.log(data);
      setPost(data);
    };
    fetchData();
  }, [match.params.id]);

According to the offical react documentation - the dependency array should includes all values from the component scope (such as props and state) that change over time and that are used by the effect.根据官方 React 文档 - the dependency array should includes all values from the component scope (such as props and state) that change over time and that are used by the effect.

You can check here for more info - Official doc link您可以在此处查看更多信息 - 官方文档链接

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

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