问题
function Header(props) {
const [ serverData, setServerData ] = useState({});
fetch('http://localhost:4001/api')
.then(res => res.json())
.then((data) => {
setServerData(data);
console.log(data);
});
return (
<div>{serverData}</div>
);
}
I'm trying to make this functional React component to get data from express api.
My code editor keep shutting down, I think that receiving data part is in the loop.
How can I make this functional component to fetch the data just once, without using componentdidmount or class type component.
I tried useCallback, it did not work for me..
回答1:
Use useEffect hook if you want to do this. If will happen once unless the dependencies change (no dependencies listed here).
function Header(props) {
const [ serverData, setServerData ] = useState({});
useEffect(() => {
fetch('http://localhost:4001/api')
.then(res => res.json())
.then((data) => {
setServerData(data);
console.log(data);
});
}, []);
return (
<div>{serverData}</div>
);
}
来源:https://stackoverflow.com/questions/61945129/how-can-i-receive-data-that-was-sent-by-express-on-functional-component