【发布时间】: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