gpt4 book ai didi

reactjs - 如何在没有 useEffect 或 setState 函数的情况下重新触发钩子(Hook)?

转载 作者:行者123 更新时间:2023-12-04 01:05:31 25 4
gpt4 key购买 nike

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

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

这是自定义钩子(Hook)的样子:

//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 };

这就是我使用这个钩子(Hook)的方式:
//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>
);
}

最佳答案

添加 urluseFetch hook 的依赖项数组这将确保效果将在 url prop 时重新运行。变化

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

关于reactjs - 如何在没有 useEffect 或 setState 函数的情况下重新触发钩子(Hook)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57025289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com