【发布时间】:2017-05-08 07:17:39
【问题描述】:
我有一个 react 应用程序,我想异步获取一些数据,对其进行处理,更改当前组件状态,然后将其作为 props 传递给渲染中的另一个组件。我尝试在 componentWillMount 中获取它,但似乎渲染仍然在获取数据之前发生。什么是可行的解决方案?我还尝试在 ES6 构造函数中获取数据,但问题仍然存在。
非常感谢任何帮助!
【问题讨论】:
标签: reactjs ecmascript-6
我有一个 react 应用程序,我想异步获取一些数据,对其进行处理,更改当前组件状态,然后将其作为 props 传递给渲染中的另一个组件。我尝试在 componentWillMount 中获取它,但似乎渲染仍然在获取数据之前发生。什么是可行的解决方案?我还尝试在 ES6 构造函数中获取数据,但问题仍然存在。
非常感谢任何帮助!
【问题讨论】:
标签: reactjs ecmascript-6
那么,获取数据的理想位置是 componentWillMount 函数,但是由于异步特性,您的子组件可能会在获取数据之前被渲染,因此您可以做两件事。
保持一个加载状态,在获取结果之前不渲染组件,例如:
constructor() {
super();
this.state = {
isLoading: true,
// other states
}
}
componentWillMount() {
//your async request here
}
render() {
if(this.state.isLoading) {
return null; // or you can render laoding spinner here
} else {
return (
//JSX here with the props
)
}
}
另一种方法是有一个空的道具并在子组件中执行检查:
constructor() {
super();
this.state = {
someProps: null;
}
}
componentWillMount() {
//your async request here
}
render() {
return (
<Child someProps={this.state.someProps}/>
)
}
儿童
render() {
if(this.props.someProps == null)
return null;
else {
return (//JSX contents here);
}
}
【讨论】: