如何在react render函数中异步等待? [英] How to async await in react render function?

查看:1905
本文介绍了如何在react render函数中异步等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对async await非常熟悉,但是对后端nodejs很熟悉.但是我遇到了一种情况,我必须在前端使用它.

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.

我正在获取对象数组,并且在该对象中,我获取了lat lng个地方.现在,使用react-geocode可以获取单个lat lng的地名,但是我想在map函数中使用该名称来获取地名.因此,据我们所知async调用,我必须在那儿使用async await.

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.

这是代码

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>
  )
}

但是当我在此处将map函数与async一起使用时,它不会返回任何内容.谁能帮助我哪里出问题了?

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

谢谢!

推荐答案

您应始终将获取数据等关注事项与显示数据等关注事项分开.这里有一个父组件,该组件通过AJAX提取数据,然后在输入数据时有条件地呈现纯功能子组件.

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>
);

我实际上并没有运行它,因此它们可能是一些小错误,如果您的数据记录具有唯一的ID,则应将其用于键属性而不是数组索引,但是会得到一个启发.

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.

相同的东西,但使用钩子更简单,更短:

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} />
}

这篇关于如何在react render函数中异步等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆