小编Pie*_*rry的帖子

React useEffect 在其依赖数组中有一个 spread 元素

我正在尝试构建一个自定义挂钩来处理异步调用的加载和错误行为。

我想像这样使用它:

const { loading, error} = useFetch(fetchUser, id)

或者

const {loading, error } = useFetch(updateUserName, id, name)

到目前为止,我有一些看起来像这样的东西:

function useFetch(fetchFn, ...params) {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  useEffect(() => {
    fetchFn(...params)
      .then(() => {
        setLoading(false);
      })
      .catch(() => {
        setError(true);
      });
  }, [...params, fetchFn]);

  return { loading, error };
}

Run Code Online (Sandbox Code Playgroud)

我遇到了麻烦,useFetch(fetchFn, ...params)因为params每次调用都会创建一个新数组。所以我不能在依赖数组中使用它。但我不能使用传播运算符。

是否有可能实现我正在尝试做的事情?

reactjs react-hooks

5
推荐指数
1
解决办法
3035
查看次数

标签 统计

react-hooks ×1

reactjs ×1