如何在反应渲染功能中异步等待? [英] How to async await in react render function?

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

问题描述

我非常熟悉async await,但使用后端nodejs.但是我遇到了一个场景,我必须在前端使用它.

我正在获取对象数组,并且在这些对象中我正在获取位置的 lat lng.现在使用 react-geocode 我可以获得单个 lat lng 的地名,但我想在地图函数中使用它来获取地名.所以正如我们所知,async 调用我必须在那里使用 async await.

这是代码

从react-geocode"导入地理编码;渲染 = 异步() =>{常量{阶段,获取公司用户骑行数据} = this.props返回 (<div>await Promise.all(_.get(this.props, 'getCompanyUserRidesData', []).map(async(userRides,index) => {const 地址 = 等待 Geocode.fromLatLng(22.685131,75.873468)console.log(address.results[0].formatted_address)返回 (<tr key={index}><td>{address.results[0].formatted_address}</td><td>果阿</td><td>asdsad</td><td>{_.get(userRides,'driverId.email', '')}</td><td>{_.get(userRides,'driverId.mobile', '')}</td></tr>)}))</tbody>

)}

但是当我在这里使用 async 和 map 函数时,它不会返回任何内容.任何人都可以帮助我哪里出错了吗?

解决方案

您应该始终将获取数据等关注点与显示数据等关注点分开.这里有一个父组件,它通过 AJAX 获取数据,然后在数据进来时有条件地呈现一个纯函数式子组件.

class ParentThatFetches 扩展 React.Component {构造函数(){this.state = {};}组件DidMount(){fetch('/some/async/data').then(resp => resp.json()).then(data => this.setState({data}));}使成为 () {{this.state.data &&(<子数据={this.state.data}/>)}}}const Child = ({data}) =>(<tr>{data.map((x, i) => ({x}))}</tr>);

我实际上并没有运行它,所以它们可能是一些小错误,如果你的数据记录有唯一的 id,你应该将它们用于键属性而不是数组索引,但你得到了 jist.

更新

同样的事情,但使用钩子更简单、更短:

const ParentThatFetches = () =>{const [数据,更新数据] = useState();useEffect(() => {const getData = async() =>{const resp = await fetch('some/url');const json = 等待 resp.json()更新数据(json);}获取数据();}, []);返回数据 &&<子数据={数据}/>}

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?

解决方案

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

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

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