”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何在 React 渲染函数中有效使用异步调用?

如何在 React 渲染函数中有效使用异步调用?

发布于2024-12-21
浏览:830

How to Effectively Use Asynchronous Calls in React Render Functions?

在 React 渲染函数中使用 Async/Await:另一种方法

React 应用程序中经常会遇到异步编程,特别是在处理外部事务时数据来源。然而,直接在 React 的 render 函数中使用 async 和 wait 可能会导致意外的结果。

为了在 React 中有效地合并异步调用,常见的方法是利用状态管理技术。这涉及到在单独的生命周期方法中获取数据,例如 componentDidMount 或使用 useEffect 等挂钩,并在数据可用后更新状态。

考虑以下示例:

class ParentThatFetches extends React.Component {
  constructor() {
    this.state = { data: null };
  }

  componentDidMount() {
    fetch("/some/async/data")
      .then(resp => resp.json())
      .then(data => this.setState({ data }));
  }

  render() {
    return this.state.data ? (
      
    ) : null;
  }
}

const Child = ({ data }) => (
  
    {data.map((x, i) => (
      {x}
    ))}
  
);

在此方法中,ParentThatFetches 组件异步获取数据并相应地更新其状态。一旦数据可用,它就会渲染子组件,该组件显示数据。

替代方法:服务器端组件

React服务器组件,在React 18中引入,提供另一种在 React 应用程序中处理异步数据的方法。与传统的客户端渲染模型不同,React Server Components 在服务器上渲染,允许您在 HTML 发送到客户端之前获取和处理数据。

下面是一个利用 React Server Components 的更新示例:

import Geocode from "react-geocode";
import _ from "lodash-es";

const getAddressData = async (getCompanyUserRidesData = []) =>
  Promise.all(
    getCompanyUserRidesData.map(async (userRides) => {
      const addr = await Geocode.fromLatLng(22.685131, 75.873468);
      const address = addr.results[0].formatted_address;
      const email = _.get(userRides, "driverId.email", "");
      const mobile = _.get(userRides, "driverId.mobile", "");
      return { address, email, mobile };
    })
  );

async function GeoServerComponent({ phase, getCompanyUserRidesData }) {
  const data = await getAddressData(getCompanyUserRidesData);
  return (
    
        {data.map(({ address, email, mobile }, index) => (
          
        ))}
      
{address} Goa asdsad {email} {mobile}
); }

在此示例中,getAddressData 函数在服务器上异步获取地址。然后,GeoServerComponent 函数接收地址作为 props,并在服务器上呈现必要的 HTML。这种方式保证了在HTML发送到客户端之前数据已经准备好,解决了直接在render函数中使用async和await时遇到的问题。

版本声明 本文转载于:1729236561如有侵犯,请联系[email protected]删除
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3