javascript - React将ajax数据传递给孩子
问题描述
如何从 ajax 调用请求的父数据传递给子组件?例如我有这样的代码
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
async componentDidMount() {
const response = await fetch();
this.setState(response.data);
}
render() {
return (
<ChildComponent data={this.state} /> // data={}
);
}
}
这里的问题是 ChildComponent 将在获取数据之前挂载,因此我将在 ChildComponent 中获取空对象数据。
解决方案
检查数据是否可用
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
async componentDidMount() {
const response = await fetch();
this.setState(response.data);
}
render() { // Return if response is Object
return Object.keys(this.state).length > 0
? <ChildComponent data={this.state} /> // data={}
: <div>Loading...</div>
}
render() { // Return if response is Array
return this.state.length > 0
? <ChildComponent data={this.state} /> // data={}
: <div>Loading...</div>
}
}
推荐阅读
- jquery - 如果箭头键不在文本/输入框中,您如何告诉 jQuery 检测箭头键
- json - 使用 pandas 将 Google 表格数据转换为特定的嵌套 JSON 架构
- python - 如果列表已排序,我必须创建一个返回 True 或 False 的函数
- javascript - 增加 Javascript 中的 setTimeout 间隔
- java - 如何检查字符串是否与java中的格式匹配?
- swiftui - 捆绑
在 SwiftUI 视图 TextField 上 - angular - 如何通过 Angular CLI 生成带有属性选择器的 Angular 组件
- ios - TTTAttributedLabel,颜色变化仅在控制器第一次在 Swift 中启动时起作用
- python - 如何在streamlit中使用多选执行特定任务?
- node.js - 如何通过 mongoDB 上给出的 id 从数据库中获取正确的对象?