首页 > web前端 > js教程 > 正文

如何在 React 渲染函数中异步获取数据

DDD
发布: 2024-10-18 15:25:29
原创
966 人浏览过

How to Asynchronously Fetch Data in React Render Functions

How to Use async/await in React Render Functions

In React, the render function is typically intended for pure, synchronous operations. However, in certain scenarios, you may encounter the need to perform asynchronous tasks within this function. This article will address how to effectively use the async/await syntax in the render function.

Understanding the Issue

As the question highlights, attempting to use async/await directly within the map function in the render function can result in unexpected behavior. This is because the map function expects synchronous operations, and attempting to perform asynchronous calls within it can disrupt the flow of the rendering process.

Separating Data Fetching from Displaying

To resolve this issue, it's recommended to separate the data fetching process from the display logic. Instead of performing asynchronous operations within the render function, it's more appropriate to initiate the data fetching in a separate component or hook.

Asynchronous Data Fetching in Parent Component

In this approach, you create a parent component (e.g., ParentThatFetches) responsible for making asynchronous requests and managing the data. Utilizing the lifecycle methods or hooks, the parent component fetches the data and stores it in the state. Subsequently, the parent component conditionally renders a pure functional child component (e.g., Child) that receives the fetched data as props.


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 }) => (

{data.map((x, i) => (<td key={i}>{x}</td>))}
登录后复制


);

Fetching Data Using Hooks

With the advent of hooks in React, data fetching can be simplified further. The following code snippet demonstrates how to use hooks to fetch data asynchronously and update the state accordingly:


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 &&
}

以上是如何在 React 渲染函数中异步获取数据的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!