【问题标题】:Nextjs Fetch data when reloading the pageNextjs 在重新加载页面时获取数据
【发布时间】:2020-02-10 12:12:05
【问题描述】:

在 React 中,我们在重新加载页面时使用 useEffect 获取数据:

useEffect(() => {
  let ignore = false
  const fetchingData = async () => {
    const res = await fetch(<your_path>)
    const data = await res.json()
    if (!ignore) setData(data)
  }; 
  fetchingData()
  return () => { ignore = true }
}, [])

但是如何在 Next.js 中做到这一点?当页面重新加载时,Fetch 不会在 getInitialProps 中触发。

【问题讨论】:

  • 你的问题就是我的答案,谢谢。
  • @FatemehQasemkhani,我的问题是基于我在 next.js 中的无能,后来我意识到 getInitialProps 中 axios 请求的问题。很高兴为您提供帮助!:)

标签: javascript html reactjs fetch next.js


【解决方案1】:

使用 axios 或 isomorphic-unfetch。它们可以在客户端和服务器环境中工作。 Node.js 环境中不存在 Fetch API。它。如果您仍想在客户端代码中使用 Fetch API,则应使用 isomorphic-unfetch。当您在浏览器中时,它使用 unfetch polyfill。如果您的代码在 Node.js 中运行,它会切换到 node-fetch。

import "axios" from "axios"

static async getInitialProps(){
    const res=await axios.get('url')//
    const data=res.data
    return {data}
}

更新

除了客户端的 fetch() 之外,Next.js 还在 Node.js 环境中填充了 fetch()。您可以在服务器代码(例如 getStaticProps/getServerSideProps)中使用 fetch(),而无需使用 polyfill,例如 isomorphic-unfetch 或 node-fetch。

https://nextjs.org/docs/basic-features/supported-browsers-features

【讨论】:

  • 我不确定更新何时到来,但在撰写此评论时,Next 有一个用于 fetch 的 polyfill,可在客户端和服务器上运行。
  • @dkapur17 你是对的。我需要更新答案
【解决方案2】:

Next.js 中,您通常使用getInitialProps 中的HTTP 请求加载数据,然后您可以将它们用作道具:

const App = props => (
  <Layout>
  {props.data}
    ...
  </Layout>
);

App.getInitialProps = async function() {
  const res = await fetch(<your_path>)
  const data = await res.json()
  return {
   data
  }
};

export default App;

【讨论】:

  • 看起来它只适用于路线更改,但不适用于页面刷新
  • 刷新页面时,仍应调用 getInitialProps。您的问题的目的是找到您应该在何处/何时进行 fetch 调用并更新您的道具。我给了你标准答案:使用 getInitialProps 但是如果你需要在一个组件中而不是在页面中使用 componentDidMount
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-26
  • 2021-12-27
  • 1970-01-01
  • 2011-11-13
  • 1970-01-01
  • 2021-07-06
  • 1970-01-01
相关资源
最近更新 更多