javascript - 如何使用两个返回语句在 React 组件中设置三元运算符“加载”Div?
问题描述
我使用的 API 很慢。我的 React 组件使用 FetchAPI 并且有两个返回语句。
我想合并一个三元运算符条件,在等待这样的数据时显示“正在加载..” div :https ://codesandbox.io/s/api-fetch-using-usestate-useeffect-k024k
如何在下面的代码中包含带有两个返回语句的“加载”三元组?注意:我大大减少了我的代码,以免让任何人发疯,所以我只包括了整体结构。别客气!
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount() {
fetch('https.data.json')
.then(response => response.json())
.then(data => this.setState({ data: data}))
}
render() {
let theList = this.state.map((item, id) => {
return (
<Card>A bunch of API Stuff </Card>
);
})
return (
<div className="search-wrap">
<Row>
{theList}
</Row>
</div>
)
}
}
export default App;
解决方案
只需在您的状态中添加一个布尔字段,表明正在加载数据。
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
loading: true, // this one
};
}
componentDidMount() {
fetch('https.data.json')
.then(response => response.json())
.then(data => this.setState({ data: data, loading: false }))
}
render() {
if (this.state.loading)
return <div>Loading...</div>
let theList = this.state.map((item, id) => {
return (
<Card>A bunch of API Stuff </Card>
);
})
return (
<div className="search-wrap">
<Row>
{theList}
</Row>
</div>
)
}
}
export default App;
推荐阅读
- python - python中的极端浮点精度数1.0-(0.1^200)
- fastapi - Tortoise-orm,fastapi 递归模型
- unity3d - Unity:在单独的脚本中调用方法时出现空异常
- c++ - 程序不会在while循环中显示信息
- jenkins - jenkins 中的 owasp zap 插件问题
- python - 如何在 Jupyter 笔记本中读取伪装成 Excel 文件的“Web 存档”文件?
- azure - 使用 .Net 创建转换的 Azure 媒体服务会出现冲突错误
- android-studio - Android Studio-android Layout Preview 卡住加载
- javascript - javascript中toString的作用是什么?
- c++ - 从 UTC 日期字符串转换为 Unix 时间戳并返回