在Material-UI List for React中使用从React组件状态异步获取的ListItem组件

Using asynchronous obtained ListItem components from the state of a React component in Material-UI List for React

http://www.material-ui.com/#/components/list 中的 List 组件不呈现异步接收的元素,怎么办?

我在组件的 render() 方法中使用列表的方式:

<List children={this.state.elements} />

填写我的状态:

constructor(props) {
    super(props);
    this.state = {elements: []};
}

async componentDidMount() {
    this.setState({elements: this.getInitialState()});
}

async getInitialState() {
      var elements = [];
      const response = await fetch('api/endpoint/elements');
      const result = await response.json();
      if (result.status = "success") {
          elements.push(<ListItem primaryText="Dummy Data" />);
      }
      return elements;
  }

这个概念没问题,应该可行。

componentDidMount 是为小型应用程序添加异步逻辑的地方(请参阅大型应用程序的 sagas、redux 等)。

你的问题是 setState 不是一个异步函数,所以无法正确设置组件的状态。

简单的把所有的ajax逻辑componentDidMount,当ajax解析的时候,修改state。

我从来没有用 await 尝试过,所以我不能确定它是否适用于它,但它 100% 适用于 Promises(例如 fetch)

一小段伪代码:

componentDidMount(){
   //jquery's POST function, just as an example
   $.post(url).then(() => {
      this.setState({dataLoaded:true});
   });
}

您需要在 componentDidMount 中等待 getInitialState。

async componentDidMount() {
    const state = await this.getInitialState();
    this.setState({elements: state});
}

如果您想在设置状态后执行某些操作,请使用 setState 的异步包装器并等待它

  setStateAsync(state) {
    return new Promise((resolve) => {
      this.setState(state, resolve)
    });
  }