javascript - 如何在渲染页面时将更新状态传递给子组件?
问题描述
我正在使用 ReactJs。在下面的代码中,我通过在页面加载时进行 API 调用来获取数据。我填充状态属性。并将状态传递给网格和列表视图。以及我想在 Grid 或 List 组件中显示的数据。但是,状态属性值不会更改,并且不会将值传递给子组件GridView
或ListView
在呈现页面时。但是状态属性值得到更新,但我认为子组件在更新之前被渲染,这就是为什么没有值传递给子组件的原因。有没有办法在页面加载时传递更新的状态属性值?
import GridView from './gridview/Grid';
import ListView from './listview/List';
export default class Home extends Component{
constructor(props){
super(props);
this.state = {
value: this.props.value,
propertyData: []
}
}
componentDidMount() {
const success = fetch("http://Some api to get the data")
.then(res => res.json())
.then(data => this.setState({propertyData: data}));
}
static getDerivedStateFromProps(props, state){
return {
value: props
}
}
GridOrList() {
if(this.state.value.value) {
return <GridView data={this.state.propertyData}/>
}
else {
return <ListView data={this.state.propertyData}/>
}
}
render() {
return(
<div>
{this.GridOrList()}
</div>
)
}
}
解决方案
尝试在渲染函数上添加 GridOrList:
render() {
return(
<div>
{this.state.value.value ? (
<GridView data={this.state.propertyData}/>
):(
<ListView data={this.state.propertyData}/>
)}
</div>
)
}
没有this.GridOrList()
this.setState
将更新状态并执行渲染功能
推荐阅读
- vue.js - 属性或方法“标题”未在实例上定义,但在渲染期间被引用。确保此属性是反应性的
- pandas - 熊猫从列列表中分配结果
- c# - 使用 HttpClient 将图像上传到 URI
- python - 在具有两个不同公差的两列上合并,熊猫
- java - Java:在 BufferdStreamReader 中自动关闭文件以避免 FileNotFoundException(打开的文件过多)
- python - SetValue 上的 wxpython TextCtrl 分段错误
- selenium - Selenium 无法通过 ID 或 xpath 找到元素
- c# - 使用 XmlRootAttribute 实例化 XmlSerializer 时,XmlDocument 的序列化失败
- c# - 是否可以在 .Net Core 应用程序中访问 Typescript 类
- angularjs - 错误:[$compile:multidir] 多个指令 [ngSwitchWhen, ngInclude] 要求包含