react函数式组件 async await运用
222浏览 · 2024-01-26 14:14:34
在React函数式组件中使用async/await可以通过自定义的异步函数来实现。下面是一个示例:
```javascript
import React, { useState, useEffect } from 'react';
const MyComponent = () => {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const jsonData = await response.json();
setData(jsonData);
} catch (error) {
console.error('Error fetching data:', error);
fetchData();
}, []);
return (
{data ? (
{data.map((item) => (
<li key={item.id}>{item.name}</li>
) : (