How to async await in react render function?

2019-08-21 19:01发布

问题:

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 end.

I am getting array of objects and in that objects I am getting lat lng of the places. Now using react-geocode I can get the place name for a single lat lng but I want to use that inside the map function to get the places names. SO as we know it async call I have to use async await over there.

Here is the code

import Geocode from "react-geocode";
render = async() => {
  const {
    phase,
    getCompanyUserRidesData
  } = this.props   

  return (
    <div>
       <tbody>                   
        await Promise.all(_.get(this.props, 'getCompanyUserRidesData', []).map(async(userRides,index) => {
          const address = await Geocode.fromLatLng(22.685131,75.873468)
          console.log(address.results[0].formatted_address)                         
         return ( 
          <tr key={index}>
            <td>
            {address.results[0].formatted_address}
            </td>
            <td>Goa</td>
            <td>asdsad</td>
            <td>{_.get(userRides,'driverId.email', '')}</td>
            <td>{_.get(userRides,'driverId.mobile', '')}</td>
          </tr>
        )
        }))
      </tbody>
    </div>
  )
}

But when I use async with the map function here it doesn't return anything. Can anyone please help me where I going wrong?

Thank you!!!

回答1:

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, but you get the jist.