【问题标题】:next.js getInitialProps doesn't work at mobile browsernext.js getInitialProps 在移动浏览器上不起作用
【发布时间】:2021-11-13 15:46:21
【问题描述】:

我有一个应用完美在桌面上运行(没有错误)但是当我使用**移动设备**时,我发现所有页面无法触发 @ 987654322@ 仅当我通过 Link 组件导航组件

时才在客户端使用

这是我的代码:

return(
  <>
   <Head>
      <title>
        welcome to Anas Behhari | blogging posts for
        {StaticFunction.Dateit(new Date())} |
        {new Date().getFullYear() - 1 + "-" + new Date().getFullYear()}
      </title>
  </Head>
   
  <div className="main">
      <div className="container">
        <div className="row">
          <div className="col-lg-10 offset-lg-1 js-post-list-wrap Blogs-con">
            <h2 className="h4 section-title">
              <span> Latest posts </span>
            </h2>
            {Blogs.map((blog) => (
              <Article blog={blog} key={blog._id} />
            ))}
            {BlogList}
          </div>
        </div>
      </div>
    </div>

  </>
)

blogs.getInitialProps = async (ctx) => {
 try {
  const res = await axios.get("http://localhost:3000/api/blogs?offset=0&max=5");
  const Blogs = res.data;
  return { Blogs };
  } catch (error) {
  return { error };
}

};

export default blogs;

【问题讨论】:

  • 您是否收到任何错误,如果有,它们是什么?另外,您能否提供blogs 组件的其余代码(return 语句之前的代码)?
  • 返回前的代码不是探针!但只是为了让您知道,例如,当我从 URL 访问 /blogs 时,它给了我应有的一切,但是当我通过 组件导航到 /blogs 时,它给出了一个错误,即我存储博客的 Blogs 变量未定义.我忘了只在电话上提及!
  • 因为getInitialProps在需要同构代码的服务器(首页加载)和客户端(客户端导航)上运行,建议使用getServerSideProps。您是否尝试过使用它?
  • 其实我只是在 getInitialProps 函数内部进行了一些更改,然后我摆脱了 Axios 并使用了简单的 fetch 函数,它运行得非常快而且没有错误!!!我将在下面添加解决方案!谢谢@juliomalves 抽出宝贵时间,我真的很感激我的人!

标签: javascript node.js reactjs next.js


【解决方案1】:

好吧,在互联网上搜索了 2 天后,我发现我只需要在 getInitialProps 函数内部进行一些更改。

主要因素是摆脱 Axios 并用 Fetch API 替换它

export async function getStaticProps() {
    const res = await fetch(`http://localhost:8080/api/blogs}`)
    const Blogs = await res.json()
    if(!Tags) return {props:{error:true}}
    return {
     props: {
       Blogs,
     },
    }
}

如果这个解决方案不起作用getServerSideProps 而不是 getStaticProps

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 2015-05-02
    相关资源
    最近更新 更多