最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Problem with time when I navigate in my nextjs project - Stack Overflow

programmeradmin0浏览0评论

I have a doubt in my nextjs project.

I added a new route inside my header calls /files and I don't know why takes a long time to load the data when I want to return to the home.

I console.log the request I and notice calls to my API and my INDEX twice, but I'm not sure if it's a problem.

The endpoint with the data is a little slow, but I believe that if I call it inside my pages/index getInitialProps, the data it's loaded in server at the beginning, I am right? and if I am right why is it taking so long to show me the data again?

Here is my code!

Header

import React, { Component } from "react";

class Header extends Component {

  render() {
    return (
      <>
        <Navbar collapseOnSelect expand="lg" bg="light" variant="light">
            <Navbar.Toggle
              aria-controls="responsive-navbar-nav"
              style={{ outline: "0", display: 'none' }}
            />
            <Navbar.Collapse id="responsive-navbar-nav">
              <Nav className="mr-auto"></Nav>
              <Nav>
                <Link href="/" passHref>
                  <Nav.Link>
                    Home
                  </Nav.Link>
                </Link>
                <Link href="/files" passHref>
                  <Nav.Link>
                    Files
                  </Nav.Link>
                </Link>
              </Nav>
            </Navbar.Collapse>
        </Navbar>
      </>
    );
  }
}

export default Header;

pages/index

import React, { useState, useEffect } from "react";

/* Others */
import Error from "./_error";
import { getDataLatestEvents } from "../helper/api";

/* Components */
import MyComponent from "../ponents/MyComponent";

/* Bootstrap Components */
import Row from "react-bootstrap/Row";


const Index = props => {
  console.log('index*************')
  const [contentData, setData] = useState([]);
  const res = props.data.data.data;  

  useEffect(() => {
    setData(res);
  }, [props]);

  if (props.statusCode !== 200) {
    return <Error statusCode={props.statusCode} />;
  }

  return (
    <>
      <Row>
        <StyledContainer>
          <MyComponent
            data={contentData}
          />
        </StyledContainer>
      </Row>
    </>
  );
};

Index.getInitialProps = async ({ res }) => {
  try {
    let req = await getDataLatestEvents();
    return { data: req, statusCode: 200 };
  } catch (e) {
    res.statusCode = 503;
    console.log(`error /pages/index: ${e}`);
    return { data: null, statusCode: 503 };
  }
};

export default Index;

helper/api

import fetch from "isomorphic-unfetch";
const BASE_URL = "https://myendpoint/api";


export async function getDataLatestEvents() {
  const res = await fetch(`${BASE_URL}/eventos?latest`);
  let data = await res.json();
  console.log('API*************')
  return { data: data};
}

I have a doubt in my nextjs project.

I added a new route inside my header calls /files and I don't know why takes a long time to load the data when I want to return to the home.

I console.log the request I and notice calls to my API and my INDEX twice, but I'm not sure if it's a problem.

The endpoint with the data is a little slow, but I believe that if I call it inside my pages/index getInitialProps, the data it's loaded in server at the beginning, I am right? and if I am right why is it taking so long to show me the data again?

Here is my code!

Header

import React, { Component } from "react";

class Header extends Component {

  render() {
    return (
      <>
        <Navbar collapseOnSelect expand="lg" bg="light" variant="light">
            <Navbar.Toggle
              aria-controls="responsive-navbar-nav"
              style={{ outline: "0", display: 'none' }}
            />
            <Navbar.Collapse id="responsive-navbar-nav">
              <Nav className="mr-auto"></Nav>
              <Nav>
                <Link href="/" passHref>
                  <Nav.Link>
                    Home
                  </Nav.Link>
                </Link>
                <Link href="/files" passHref>
                  <Nav.Link>
                    Files
                  </Nav.Link>
                </Link>
              </Nav>
            </Navbar.Collapse>
        </Navbar>
      </>
    );
  }
}

export default Header;

pages/index

import React, { useState, useEffect } from "react";

/* Others */
import Error from "./_error";
import { getDataLatestEvents } from "../helper/api";

/* Components */
import MyComponent from "../ponents/MyComponent";

/* Bootstrap Components */
import Row from "react-bootstrap/Row";


const Index = props => {
  console.log('index*************')
  const [contentData, setData] = useState([]);
  const res = props.data.data.data;  

  useEffect(() => {
    setData(res);
  }, [props]);

  if (props.statusCode !== 200) {
    return <Error statusCode={props.statusCode} />;
  }

  return (
    <>
      <Row>
        <StyledContainer>
          <MyComponent
            data={contentData}
          />
        </StyledContainer>
      </Row>
    </>
  );
};

Index.getInitialProps = async ({ res }) => {
  try {
    let req = await getDataLatestEvents();
    return { data: req, statusCode: 200 };
  } catch (e) {
    res.statusCode = 503;
    console.log(`error /pages/index: ${e}`);
    return { data: null, statusCode: 503 };
  }
};

export default Index;

helper/api

import fetch from "isomorphic-unfetch";
const BASE_URL = "https://myendpoint/api";


export async function getDataLatestEvents() {
  const res = await fetch(`${BASE_URL}/eventos?latest`);
  let data = await res.json();
  console.log('API*************')
  return { data: data};
}
Share Improve this question edited Feb 2, 2023 at 6:39 Mayank Kumar Chaudhari 18.9k13 gold badges72 silver badges155 bronze badges asked Mar 21, 2020 at 18:04 PhilPhil 9491 gold badge10 silver badges21 bronze badges 2
  • 1 Have you tried clicking on the network tab in Chrome to see what's taking so long to load? Also, seeing two responses in the console is a problem. You may have some code somewhere that needs looking at to fix this. – Leafyshark Commented Mar 23, 2020 at 22:46
  • Yes, I checked in Network and the endpoint of getDataLatestEvents is the problem... Anyway I don 't know the console.log issue...I already checkit and I can 't find the problem... – Phil Commented Mar 25, 2020 at 13:11
Add a ment  | 

1 Answer 1

Reset to default 4

This sort of delay is often encountered when using next dev (via yarn dev or npm dev). This is because when using yarn dev, page is rebuild every time it is requested. So when you navigate back to the index page, Next.js first rebuild that page for you and then it is served. That's why there is a delay.

You should not find similar delay in production (when using next build and then next start)

Edit

getInitialProps enables server-side rendering in a page. In case you don't need to fetch any data every time the request is sent or page is reloaded, use getStaticProps instead.

发布评论

评论列表(0)

  1. 暂无评论