首页  >  文章  >  web前端  >  如何在 React 渲染函数中有效使用异步调用?

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

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-18 15:30:29255浏览

How to Effectively Use Asynchronous Calls in React Render Functions?

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

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

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

考虑以下示例:

<code class="javascript">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 ? (
      <Child data={this.state.data} />
    ) : null;
  }
}

const Child = ({ data }) => (
  <tr key={index}>
    {data.map((x, i) => (
      <td key={i}>{x}</td>
    ))}
  </tr>
);</code>

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

替代方法:服务器端组件

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

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

<code class="javascript">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 (
    <table>
      <tbody>
        {data.map(({ address, email, mobile }, index) => (
          <tr key={index}>
            <td>{address}</td>
            <td>Goa</td>
            <td>asdsad</td>
            <td>{email}</td>
            <td>{mobile}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}</code>

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

以上是如何在 React 渲染函数中有效使用异步调用?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn