How to async await in react render function?

后端 未结 1 410
一整个雨季
一整个雨季 2020-12-07 00:46

I am pretty much familiar with the async await but with back end nodejs. But there is a scenario came across to me where I have to use it on front

相关标签:
1条回答
  • 2020-12-07 01:40

    You should always separate concerns like fetching data from concerns like displaying it. Here there's a parent component that fetches the data via AJAX and then conditionally renders a pure functional child component when the data comes in.

    class ParentThatFetches extends React.Component {
      constructor () {
        this.state = {};
      }
    
      componentDidMount () {
        fetch('/some/async/data')
          .then(resp => resp.json())
          .then(data => this.setState({data}));
      }
    
      render () {
        {this.state.data && (
          <Child data={this.state.data} />
        )}
      }
    }
    
    const Child = ({data}) => (
      <tr>
        {data.map((x, i) => (<td key={i}>{x}</td>))}
      </tr>
    );
    

    I didn't actually run it so their may be some minor errors, and if your data records have unique ids you should use those for the key attribute instead of the array index, but you get the jist.

    UPDATE

    Same thing but simpler and shorter using hooks:

    const ParentThatFetches = () => {
      const [data, updateData] = useState();
      useEffect(() => {
        const getData = async () => {
          const resp = await fetch('some/url');
          const json = await resp.json()
          updateData(json);
        }
        getData();
      }, []);
    
      return data && <Child data={data} />
    }
    
    0 讨论(0)
提交回复
热议问题