To properly use React, you should keep data inside the state, so React's virtual DOM can properly render items according to that data (for your case).
Also, no need to chain .then
whilst using await
.
On another note, it is weird that you are using axios.post
instead of axios.get
for fetching the data, just a piece of friendly advice.
The reason why your const dataList = null
never gets updated is because you are initializing it inside the render function, meaning every time the state gets updated (setIsLoading
) your dataList
gets reinitialized to null
const Start = () => {
const [isLoading, setIsLoading] = useState(false);
const [dataList, setDataList] = useState([]);
useEffect(() => {
const getData = async () => {
setIsLoading(true);
const response = await axios.post('/api/getData');
setIsLoading(false);
setDataList(response.data.result);
};
getData();
}, []);
if (isLoading) {
return <div>...Loading...</div>;
}
return (
<div>
{dataList.map((item, idx) => (
<p>{item[0].dataName}</p>
))}
</div>
);
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…