【问题标题】:using async-await in react在反应中使用异步等待
【发布时间】: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))加载到我的组件中,它就可以正常工作。 但是组件EnterpriseLogoEnterpriseInfo 使用hit 属性引用例如props.hit.objectID,它会使应用程序崩溃,因为这个引用还不存在。

我认为我在某个地方遇到了设计问题,但我不知道该去哪里。

【问题讨论】:

  • 你在 webpack 配置中使用插件 transform-async-to-generatorstage-1 预设
  • 这是个好问题,我正在使用 create-react-app。我看到它包含在babel-plugin-transform-async-to-generator
  • 你能在componentDidMount中做this.setState({hit: h}, ()=&gt; {this.state.hit});
  • 当您在构造函数中初始化state.hit 对象时,您必须确保子组件所需的所有props 都存在并默认存在。否则,渲染方法将在初始渲染期间崩溃,因为异步调用在渲染发生之前不会完成。
  • @hazardous 非常感谢,这很有意义!我以为会有别的东西......

标签: reactjs async-await


【解决方案1】:

回答我自己, 使用子组件所需的所有道具初始化 state.hit 解决了这个问题。

【讨论】:

    猜你喜欢
    • 2019-07-23
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 2022-06-29
    • 2022-01-09
    相关资源
    最近更新 更多