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

bab*_*830 -1 axios react-hooks use-effect

我已经创建了一个 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);
      });

  }, []);
Run Code Online (Sandbox Code Playgroud)

Ali*_*deh 5

如果您不想禁用 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]);
Run Code Online (Sandbox Code Playgroud)

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