我找到了一个非常有趣的钩子,我想在useEffect中使用这个钩子(这违反了规则)
const useFetch = (url, options) => {
const [response, setResponse] = React.useState(null);
const [error, setError] = React.useState(null);
React.useEffect(() => {
const fetchData = async () => {
try {
const res = await fetch(url, options);
const json = await res.json();
setResponse(json);
} catch (error) {
setError(error);
}
};
fetchData();
}, []);
return { response, error };
};function App() {
const res = useFetch("example.com", {});
useEffect(() => {
// use the hook and make a secondary request
}, [])为了支持这一点,我需要做什么修改?在useEffect内部不能调用AFAIK钩子
可能是一个新参数,它将setUrl并再次运行它?
发布于 2021-05-28 10:02:34
似乎您希望在某些状态或变量更改时在钩子中执行fetch请求。
您不能有条件地调用钩子,也不能根据文档中提到的钩子规则在另一个钩子中执行它。
要做您想做的事情,您可以修改您的自定义钩子以接受数组作为一个依赖项传递给它内部的useEffect,并且当任何依赖项发生变化时,它都会调用api。
const useFetch = (url, options, deps = []) => {
const [response, setResponse] = React.useState(null);
const [error, setError] = React.useState(null);
React.useEffect(() => {
const fetchData = async () => {
try {
const res = await fetch(url, options);
const json = await res.json();
setResponse(json);
} catch (error) {
setError(error);
}
};
url && fetchData();
}, deps);
return { response, error };
};然后把它当作
function App() {
const res = useFetch("example.com", {}, [someVariable]);
...
}发布于 2021-05-28 06:24:47
您不能有条件地调用useFetch,也不能在任何回调(即useEffect回调)中调用它(请参阅钩子规则),但您可以利用这样的事实,即每个呈现都以相同的顺序调用钩子。执行条件测试,并设置传递给第二个useFetch钩子的URL。在发出请求之前,更新useFetch钩子以检查是否是真实的url。
const useFetch = (url, options) => {
const [response, setResponse] = React.useState(null);
const [error, setError] = React.useState(null);
React.useEffect(() => {
const fetchData = async () => {
try {
const res = await fetch(url, options);
const json = await res.json();
setResponse(json);
} catch (error) {
setError(error);
}
};
url && fetchData();
}, []);
return { response, error };
};..。
function App() {
const res = useFetch("example.com", {});
let url = "";
if (someCondition) {
let url = ""example2.com"";
}
const res2 = useFetch("example.com", {});https://stackoverflow.com/questions/67733739
复制相似问题