javascript - 获取数据后,异步响应渲染组件
问题描述
获取数据后,我需要渲染一个组件。如果尝试立即加载数据,组件会被渲染但没有数据显示。
class App extends React.Component {
//typical construct
getGames = () => {
fetch(Url, {})
.then(data => data.json())
.then(data => {
this.setState({ links: data });
})
.catch(e => console.log(e));
};
componentDidMount() {
this.getGames();
}
render() {
return (
<div className="App">
<Game gameId={this.state.links[0].id} /> //need to render this part
after data is received.
</div>
);
}
}
解决方案
您可以保留一个名为 eg 的附加状态,并在您的网络请求完成之前isLoading
进行渲染。null
例子
class App extends React.Component {
state = { links: [], isLoading: true };
getGames = () => {
fetch(Url, {})
.then(data => data.json())
.then(data => {
this.setState({ links: data, isLoading: false });
})
.catch(e => console.log(e));
};
componentDidMount() {
this.getGames();
}
render() {
const { links, isLoading } = this.state;
if (isLoading) {
return null;
}
return (
<div className="App">
<Game gameId={links[0].id} />
</div>
);
}
}
推荐阅读
- html - 微调器未显示在引导程序 4.0.0 中
- javascript - 在服务器上设置 HTML 输入无效
- flutter - 在 Flutter 的底部导航栏上显示抽屉
- swift - 不推荐使用未标记尾随闭包的向后匹配...有什么方法可以使其静音,而不是停止使用尾随闭包?
- google-cloud-platform - 删除与 google 帐户关联的电子邮件后,您的 google 帐户和 google 项目会发生什么情况
- ios - 在 UILabel 上获取文本字符框
- sql - 更新数百万条记录 Oracle
- xslt-2.0 - 如何在 xslt 中拆分和打印值?
- swift - 为什么我的 SwiftUI VStack 没有正确对齐?
- python - 在图像的中心绘图