我正在使用ReactJs。在下面的代码中,我通过在页面加载时调用API来获取数据。然后填充state属性。并将状态传递到网格和列表视图。而这些数据我想显示在Grid或List组件中。但是,状态属性值不会更改,并且在呈现页面时不会将任何值传递给子组件GridView
或ListView
。但是状态属性值得到更新,但是我认为子组件在更新之前就已呈现,这就是为什么没有值传递给子组件的原因。有没有办法在页面加载时传递更新的sate属性值?
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>
)
}
}
最佳答案
状态更改后,所有依赖状态的组件都将重新呈现。您可以在从api提取数据时使用加载程序:
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
value: this.props.value,
propertyData: [],
loading: true // Add loading state
};
}
componentDidMount() {
const success = fetch("http://Some api to get the data")
.then(res => res.json())
.then(data => this.setState({ propertyData: data, loading: false })); // Reset loading state
}
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 this.state.loading ? (
<p>Loading data...</p>
) : (
<div>{this.GridOrList()}</div>
);
}
}
关于javascript - 如何在页面呈现时将更新后的状态传递给子组件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58496587/