首页 > 解决方案 > 如何在渲染页面时将更新状态传递给子组件?

问题描述

我正在使用 ReactJs。在下面的代码中,我通过在页面加载时进行 API 调用来获取数据。我填充状态属性。并将状态传递给网格和列表视图。以及我想在 Grid 或 List 组件中显示的数据。但是,状态属性值不会更改,并且不会将值传递给子组件GridViewListView在呈现页面时。但是状态属性值得到更新,但我认为子组件在更新之前被渲染,这就是为什么没有值传递给子组件的原因。有没有办法在页面加载时传递更新的状态属性值?


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>
   )
 }
}

标签: javascriptreactjs

解决方案


尝试在渲染函数上添加 GridOrList:

 render() {
   return(
     <div>
       {this.state.value.value ? (
         <GridView data={this.state.propertyData}/>
       ):(
         <ListView data={this.state.propertyData}/>
       )}
     </div>
   )
 }

没有this.GridOrList()

this.setState将更新状态并执行渲染功能


推荐阅读