异步渲染组件

时间:2019-05-02 12:09:49

标签: reactjs typescript

我阅读了此Reactjs async rendering of components并尝试使用自己的代码,但出现了错误:

  

对象作为React子对象无效(找到:[object Promise])。如果   您本打算渲染子级集合,而是使用数组。

我不知道为什么它不起作用。请帮助我!

 constructor(props) {
    super(props);
    this.state = { asyncComponent: null };
  }

public componentDidMount() {
    import(`../../i18n/locales/${this.props.lang}`).then(o => {
      this.setState({
        asyncComponent: (
          <CustomSelects
            options={o.option}
            formattedMessageId="createroom_genre"
            value={this.props.genre}
            handleValueChange={this.handleGenreChange}
          />
        )
      });
    });
  }

 public render() {
     return (
            //...
           {this.state.asyncComponent ? (
              this.state.asyncComponent
            ) : (
              <div />
            )}
           //...
    )
 }

1 个答案:

答案 0 :(得分:0)

  constructor(props) {
    super(props);
    this.state = { options: null };
    //...
  }

  public componentDidMount() {
    this.props.initCreateRoomState();
    this.getSelectsIntl();
  }

  public componentWillUnmount() {}

  public componentWillReceiveProps() {
    this.getSelectsIntl();
  }

  private getSelectsIntl = () => {
    import(`../../i18n/locales/${this.props.lang}`).then(o => {
      this.setState({
        options: o.options
      });
    });
  }

  public render() {
      return (
            {this.state.options ? (
                <CustomSelects
                  options={this.state.options}
                  formattedMessageId="createroom_genre"
                  value={this.props.genre}
                  handleValueChange={this.handleGenreChange}
                />
              ) : (
                <div />
              )}
//...