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

请问,在React中,

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

image.png

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>
}
阅读 3.2k
3 个回答

当做一个函数去看,函数组件 Page 渲染过程中即执行

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

export async function getServerSideProps(context) {
  const data = await getData();

  return {
    props: { data }, // will be passed to the page component as props
  };
}

export default function Page({ data }) {
  return <main>{/* 使用你的数据 */}</main>;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题