当按下按钮时,我试图使用useFetch从包中发出请求。这是我的密码
import React, { useState } from 'react';
import useFetch from 'react-fetch-hook';
import { Button } from 'react-bootstrap';
const Component = () => {
const [message, setMessage] = useState(false);
const handleOnClick = () => {
const { isLoading, data } = useFetch(
'https://raw.githubusercontent.com/markmclaren2/sample_json/main/user.json'
);
if (isLoading) {
setMessage('Loading...');
} else {
setMessage(`Received id: ${data.id}`);
}
};
return (
<div>
<Button onClick={handleOnClick}>Load Data</Button>
<div>{message}</div>
</div>
);
};
export default Component;我遇到了这个错误
React Hook "useFetch" is called in function "handleOnClick" that is neither a React function component nor a custom React Hook function.
当用户按下按钮并显示“加载.”时,调用useFetch的正确方法是什么?结果信息呢?
发布于 2022-06-14 08:38:26
你好,也许要做这样的事情:
import React, { useState } from "react";
import useFetch from "react-fetch-hook";
import { Button } from "react-bootstrap";
export default function App() {
const [message, setMessage] = useState("");
const [isClicked, setIsClicked] = useState(false);
const {
isLoading,
data
} = useFetch(
"https://raw.githubusercontent.com/markmclaren2/sample_json/main/user.json",
{ depends: [isClicked], formatter: (response) => response.text() }
);
const handleOnClick = () => {
setIsClicked(true);
if (isLoading) {
setMessage("Loading...");
} else {
setMessage(data as string);
}
};
return (
<div>
<Button onClick={handleOnClick}>Load Data</Button>
<div>{message}</div>
</div>
);
}我在这里还准备了一个码箱,这样你就可以查看了。
https://stackoverflow.com/questions/72613765
复制相似问题