import React, {useState, useEffect, Component} from 'react';
import {Grid, Paper, TextField} from '@material-ui/core'
import DataManager from './../data_manager/data_manager'
const dataManager = new DataManager();
const Tile = (props)=>{
// Initializing State Variables
const [state, setState] = useState({
data : {}
})
const { status, data, error, isFetching } = useQuery("data",async()=>{
const res = await fetch("localhost:8000");
return res.json()
}
if(status==="success"){
setState({data})
}else{
return(<p>Doing</p>)
}
}
此代码将导致无限循环,在此循环中渲染将继续进行。
我认为这是因为setState导致useQuery再次执行以再次设置状态,依此类推。
感谢您的帮助。我想将从useQuery获得的数据存储在状态变量中。
TIA。
答案 0 :(得分:1)
您可能现在要使用useEffect
来获取每个渲染器上的内容:
const Tile = (props) => {
const [state, setState] = useState({
data: {},
});
const { status, data, error, isFetching } = useQuery("data", async () => {
const res = await fetch("localhost:8000");
return res.json();
});
useEffect(() => {
if (status === "success") {
setState({ data });
}
}, [status, data]);
return status === success ? (
<div>Success and use data</div>
) : (
<div>Loading</div>
);
};