reactjs - 传递给子组件的父组件状态未定义
问题描述
在我的父组件中,我有一个发出 GET 请求的函数。我将响应 JSON 存储在父组件的状态中,并将状态传递给子组件,然后子组件以特定格式呈现响应(在此,它填充一个表)。
这是父组件的代码:-
ParentComponent {
sendGETRequest() {
/* Fetch API code */
.then(response => response.json())
.then(response => {
this.setState({
personData: response
});
console.log(this.state.personData); //loads late
});
}
render() {
return(
<Link to="/PersonData/ViewPerson">
<input onClick={this.sendGETRequest} />
<Route
path="/PersonData/ViewPerson"
render={() => <ViewPersonTable pData={this.state.personData} />}
/>
);
}
}
这是子组件的代码:-
ChildComponent{
render(){
console.log(this.props.pData); //This loads before the console.log in parent and is undefined
return(
);
}
}
我的问题是,据我所知,setState 发生在子组件已经呈现之后,因此我传递给子组件的状态是“未定义”。我该如何解决?
解决方案
您可以使用条件渲染;
<Route
path="/PersonData/ViewPerson"
render={() => this.state.personData ? <ViewPersonTable pData={this.state.personData} /> : null}
/>
推荐阅读
- flutter - 无法访问冻结类上的 copyWith 方法
- swift - 澄清 Swift 字典和 map[x]!.append(product) 到 Kotlin 的可能翻译
- javascript - 排序对象和嵌套对象
- mysql - MySQL CASE 函数给出了意想不到的结果
- node.js - JEST expect.anything() 或 null
- python - 尝试导入 minerl 时出现错误
- python - Python:将文件名更改为列表中的人名
- css - CSS Grid 忽略最大高度
- reactjs - 尝试在 Devise (+ Rails API) 上添加可恢复选项
- html - 为什么我的html链接点击后不变色