React Hooks:如何在渲染前等待数据被获取 [英] React Hooks: how to wait for the data to be fetched before rendering
本文介绍了React Hooks:如何在渲染前等待数据被获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 useEffect 钩子中有 fetch 方法:
I have fetch method in useEffect hook:
export const CardDetails = () => {
const [ card, getCardDetails ] = useState();
const { id } = useParams();
useEffect(() => {
fetch(`http://localhost:3001/cards/${id}`)
.then((res) => res.json())
.then((data) => getCardDetails(data))
}, [id])
return (
<DetailsRow data={card} />
)
}
但是在 DetailsRow
组件内部没有定义这个数据,这意味着我在获取数据之前渲染了这个组件.如何正确解决?
But then inside DetailsRow
component this data is not defined, which means that I render this component before data is fetched. How to solve it properly?
推荐答案
当数据undefined
时不要渲染它:
export const CardDetails = () => {
const [card, setCard] = useState();
const { id } = useParams();
useEffect(() => {
fetch(`http://localhost:3001/cards/${id}`)
.then((res) => res.json())
.then((data) => setCard(data));
}, [id]);
if (card === undefined) {
return <>Still loading...</>;
}
return <DetailsRow data={card} />;
};
这篇关于React Hooks:如何在渲染前等待数据被获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文