【发布时间】:2017-05-15 08:53:47
【问题描述】:
我已经浏览了很多关于这个主题的堆栈溢出问题,但我仍然不明白...... 我正在尝试这个解决方案很好地回答我的问题:https://stackoverflow.com/a/42601915/2617419
这是我所拥有的:
class EnterpriseContainer extends Component {
constructor(props) {
super(props);
this.state = {hit: props.hit};
}
async componentDidMount() {
if (this.state.hit === undefined) {
let h = await getObjectIDAsync();
this.setState({hit: h});
} else {
}
}
render() {
return (
<Grid item xs={12} sm={12} md={12} lg={12} xl={12}>
<Paper className="paper" elevation={1} style={{'paddingLeft': '0px'}}>
<Grid
container
>
<EnterpriseLogo image={this.state.hit.image}/>
<EnterpriseInfo hit={this.state.hit}/>
</Grid>
</Paper>
</Grid>
);
}
}
我知道这个逻辑是先加载反应组件,然后异步加载数据。
如果我只是将命中对象作为字符串化对象(使用JSON.stringify(hit))加载到我的组件中,它就可以正常工作。
但是组件EnterpriseLogo 和EnterpriseInfo 使用hit 属性引用例如props.hit.objectID,它会使应用程序崩溃,因为这个引用还不存在。
我认为我在某个地方遇到了设计问题,但我不知道该去哪里。
【问题讨论】:
-
你在 webpack 配置中使用插件
transform-async-to-generator和stage-1预设 -
这是个好问题,我正在使用 create-react-app。我看到它包含在
babel-plugin-transform-async-to-generator -
你能在componentDidMount中做
this.setState({hit: h}, ()=> {this.state.hit});吗 -
当您在构造函数中初始化
state.hit对象时,您必须确保子组件所需的所有props 都存在并默认存在。否则,渲染方法将在初始渲染期间崩溃,因为异步调用在渲染发生之前不会完成。 -
@hazardous 非常感谢,这很有意义!我以为会有别的东西......
标签: reactjs async-await