【问题标题】:How to re-trigger hook without useEffect or a setState function?如何在没有 useEffect 或 setState 函数的情况下重新触发钩子?
【发布时间】:2019-07-14 07:08:42
【问题描述】:

我正在使用一个自定义挂钩,该挂钩将 URL 作为参数并返回获取数据及其加载状态。因此,与大多数钩子不同,我没有在需要时设置新状态的功能,这在项目的这一点上引起了各种问题,因为我碰巧需要一种方法来重新触发该自定义钩子每次收到新的道具值。

问题是,正如预期的那样,组件的状态是在组件首次渲染时设置的,但是当它接收到新的道具时,它不会重新渲染/重新触发。

这是自定义钩子的样子:

//useFetch.js

import { useState, useEffect } from "react";

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  async function fetchUrl() {
    const response = await fetch(url);
    const json = await response.json();
    setData(JSON.parse(JSON.stringify(json)));
    setLoading(false);
  }

  useEffect(() => {
    fetchUrl();
  }, []);

  return [data, loading];
}

export { useFetch };

这就是我使用这个钩子的方式:

//repos.js

import React from "react";
import { useFetch }  from "./fetchHook";


function Repos(props) {
  const [userRepos, reposLoading] = useFetch(`https://api.github.com/users/${props.users[props.count].login}/repos`);

  return reposLoading ? (
    <div className="App">
      stuff to render if it's still loading
    </div>
  ) : (
    <div
     stuff to render if it's loaded
    </div>
  );
}

【问题讨论】:

  • @jonrsharpe 我将它传递给像${props.users[props.count].login} 这样的字符串文字,并且每次我发送新的道具值时这些道具都会更新,但 useFetch 在第一次渲染后不会再次启动。

标签: reactjs react-hooks


【解决方案1】:

url 添加到useFetch hook 的依赖数组中,这将确保在url prop 更改时重新运行效果

useEffect(() => {
  console.log("refetching url", url);
  fetchUrl();
}, [url]);

【讨论】:

  • 我不知道您可以向该数组添加一些东西,这很有意义。谢谢!我现在意识到我应该做更多的文档阅读。
  • @ÖzençB。是的,依赖数组中的所有内容都将导致重新运行效果,如果您希望效果像componentDidMount 一样提供一个空数组,如果您想在每次重新渲染时重新运行效果,根本不要提供第二个argument /跨度>
猜你喜欢
  • 2020-11-23
  • 2020-06-23
  • 2018-03-27
  • 1970-01-01
  • 2020-05-16
  • 2021-10-17
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
相关资源
最近更新 更多