javascript 如何在反应渲染功能中异步等待?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53819864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:18:19  来源:igfitidea点击:

How to async await in react render function?

javascriptreactjsasynchronouspromiseasync-await

提问by Profer

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

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

I am getting array of objects and in that objects I am getting lat lngof the places. Now using react-geocodeI can get the place name for a single lat lngbut I want to use that inside the map function to get the places names. SO as we know it asynccall I have to use async awaitover there.

我得到了对象数组,在这些对象中我得到lat lng了这些地方。现在使用react-geocode我可以获得单个的地名,lat lng但我想在 map 函数中使用它来获取地名。所以正如我们所知,async我必须async await在那里使用。

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?

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

Thank you!!!

谢谢!!!

回答by Jared Smith

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.

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

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.

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