首页 > 解决方案 > ReactJS async rendering

问题描述

I am new with React and cannot write correct code for the situation. Let me explain in the code

class Test extends React.Component {
  render() {
    // IndexedDB indexes
    const ids = ['id1', 'id2', 'id3'];

    // fetch data and build a list
    const files = ids.map((id) => 
      localforage.getItem(id).then((entry) => 
        <li key={entry.id}><img src={entry.data} /></li>
      );
    );

    return (
      <ul>{files}</ul>
    )
  }
}

What is the correct way to asynchronous load all data and display it?

标签: javascriptreactjsasynchronous

解决方案


componentDidMount您可以在钩子中执行异步逻辑并使用setState将条目置于您的状态中。

例子

class Test extends React.Component {
  state = { entries: [] };

  componentDidMount() {
    const ids = ["id1", "id2", "id3"];

    Promise.all(ids.map(id => localforage.getItem(id))).then(entries => {
      this.setState({ entries });
    });
  }

  render() {   
    return (
      <ul>
        {this.state.entries.map(entry => (
          <li key={entry.id}>
            <img src={entry.data} />
          </li>
        ))}
      </ul>
    );
  }
}

推荐阅读