Rumah >hujung hadapan web >tutorial js >Bagaimana untuk Menggunakan Async/Menunggu dengan betul dalam Fungsi Render React?

Bagaimana untuk Menggunakan Async/Menunggu dengan betul dalam Fungsi Render React?

DDD
DDDasal
2024-10-18 15:28:29617semak imbas

How to Use Async/Await Correctly in React Render Functions?

Understanding Async/Await in React Render Functions

Asynchronous programming, enabled by async/await syntax, is common in back-end development, such as Node.js, but can also be applied in front-end scenarios within React render functions.

Use Case: Geocoding with react-geocode

Consider a scenario where you need to obtain the place name for multiple locations using the react-geocode library and display them in a React table:

<code class="js">import React, { useEffect, useState } from 'react';
import Geocode from 'react-geocode';
import _ from 'lodash';

const GeocodeTable = ({ locations }) => {
  const [addresses, setAddresses] = useState([]);

  useEffect(() => {
    Promise.all(locations.map(async (loc) => {
      const address = await Geocode.fromLatLng(loc[0], loc[1]);
      return address.results[0].formatted_address;
    }))
    .then(results => setAddresses(results));
  }, [locations]);

  return (
    <tbody>
      {addresses.map((addr, idx) => (
        <tr key={idx}>
          <td>{addr}</td>
          <td>Goa</td>
          <td>asdsad</td>
          <td>{_.get(loc, 'driverId.email', '')}</td>
          <td>{_.get(loc, 'driverId.mobile', '')}</td>
        </tr>
      ))}
    </tbody>
  );
};</code>

Mistakes to Avoid

In your original code, you attempted to use async/await directly within the map function of the render function. This is not supported and will result in an empty return.

Best Practices

  • Separate Data Fetching from Displaying: The recommended approach is to separate data fetching from rendering. Use a parent component to perform asynchronous operations (like geocoding) and conditionally render a child component when the data is available.
  • Use Memoization: To optimize performance, consider using memoization techniques, such as useMemo in the parent component, to avoid redundant data fetching.
  • TypeScript Support: If using TypeScript, consider defining types for the geocoding results to improve type safety and avoid potential errors.

Atas ialah kandungan terperinci Bagaimana untuk Menggunakan Async/Menunggu dengan betul dalam Fungsi Render React?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn