当前位置: 首页 > 知识库问答 >
问题:

前端 - 请问,在React中, `const data = await getData()` 这个代码执行的时机是哪个生命周期?

淳于玺
2023-07-07

请问,在React中,

const data = await getData() 这个代码执行的时机是生命周期的哪个点?

async function getData() {
  const res = await fetch('https://api.example.com/...')
  // The return value is *not* serialized
  // You can return Date, Map, Set, etc.
 
  // Recommendation: handle errors
  if (!res.ok) {
    // This will activate the closest `error.js` Error Boundary
    throw new Error('Failed to fetch data')
  }
 
  return res.json()
}
 
export default async function Page() {
  const data = await getData()
 
  return <main></main>
}

共有1个答案

汪丁雷
2023-07-07

Page函数是不能加async的,这样返回结果是个Promise, 渲染不出来的页面的

 类似资料: