React Hooks 依赖 - 无限循环

React Hooks Dependencies - Infinite Loop

我有以下代码:

import React from "react";

export const useFetch = (promise, args = [], options = {}) => {
  const [state, setState] = React.useState({
    loading: false,
    data: null,
    error: null
  });

  if (!args) args = [];

  const fetch = React.useCallback((...args) => {
    setState({
      ...state,
      loading: true,
      error: null
    });

    return promise(...args)
      .then(response => {
        setState({
          ...state,
          loading: false,
          data: response
        });
        return response;
      })
      .catch(error => {
        setState({
          ...state,
          loading: false,
          error
        });
      });
  }, [promise, state]);

  React.useEffect(() => {
    if (options.now) {
      fetch(...args);
    }
  }, [args, fetch, options.now]);

  return {
    fetch,
    ...state
  };
};

但是 当我尝试这样使用时,我得到了一个无限 console.log 循环

const allUsers = () => Promise.resolve([{ name: 'Bruno' }])

function App() {
  const { data } = useFetch(allUsers, [], { now: true })
  console.log('->', data)
  return (
    <span>Testing hook</span>
  )
}

所有部门和 useCallback 都是来自 lint react-hooks/exhaustive-deps 的建议。那么,我做错了什么?

感谢您的帮助。

有2个问题。 1. 你的 fetch 每次都得到一个新值,因为它有状态作为依赖,这每次都会导致 useEffect 运行,所以无限循环。 2.useEffect 将 args 作为依赖项,每次也不相同,您不需要将 args 传递给 fetch,因为它已经可用,因为关闭了。

这是更新后的代码,不会进入无限循环。你可能会遇到 lint 问题,但你现在应该忽略它们,直到这个 linter 变得更标准。

const useFetch = (promise, args = [], options = {}) => {
  const [state, setState] = React.useState({
    loading: false,
    data: null,
    error: null
  });

  if (!args) args = [];

  const fetch = React.useCallback(() => {
    setState({
      ...state,
      loading: true,
      error: null
    });

    return promise(...args)
      .then(response => {
        setState({
          ...state,
          loading: false,
          data: response
        });
        return response;
      })
      .catch(error => {
        setState({
          ...state,
          loading: false,
          error
        });
      });
  }, [promise]);

  React.useEffect(() => {
    if (options.now) {
      fetch();
    }
  }, [fetch, options.now]);

  return {
    fetch,
    ...state
  };
};

const allUsers = () => Promise.resolve([{ name: 'Bruno' }])


const App = props => {
  const { data } = useFetch(allUsers, [], { now: true });
  console.log(data, "=>");
  return <input name="name" onChange={this.handleInputChange} />;
}