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

React Hook useEffect has a missing dependency: 'props.match.params.id'

我创建了一个 React 应用程序。对于数据获取,我使用了 axios。我的应用程序按预期运行良好。但是在我的终端中,我收到这样的警告 Line 34:6: React Hook useEffect has a missing dependency: 'props.match.params.id'. Either include it or remove the dependency array react-hooks/exhaustive-deps。我不想使用 // eslint-disable-next-line react-hooks/exhaustive-deps。有没有其他解决方案?

  useEffect(() => {
    axios
      .get("http://localhost:5000/students/" + props.match.params.id)
      .then(response => {
        setState({
          name: response.data.name,
          birthday: response.data.birthday,
          address: response.data.address,
          zipcode: response.data.zipcode,
          city: response.data.city,
          phone: response.data.phone,
          email: response.data.email
        });
      })
      .catch(function(error) {
        console.log(error);
      });

  }, []);

如果你不想禁用 eslint 规则,你需要遵循它,只需将 prop 添加到你的依赖数组:

  useEffect(() => {
    axios
      .get("http://localhost:5000/students/" + props.match.params.id)
      .then(response => {
        setState({
          name: response.data.name,
          birthday: response.data.birthday,
          address: response.data.address,
          zipcode: response.data.zipcode,
          city: response.data.city,
          phone: response.data.phone,
          email: response.data.email
        });
      })
      .catch(function(error) {
        console.log(error);
      });

  }, [props.match.params.id]);

这意味着如果 id 改变,你的效果将被卸载并再次调用,这似乎是有道理的,考虑到你的效果中使用了 match.params.id。