相关疑难解决方法(0)

如何在最新的Next.js中获取服务器端数据?尝试了 getStaticProps 但它没有运行并且未定义

我正在使用 Next.js 开发 Django Rest 框架,但我陷入了从 API 获取数据的困境。我在这个 url 中有数据http://127.0.0.1:8000/api/campaigns,当我访问该 url 时,我会看到数据。

问题是当我使用 Next.js 获取并控制台数据时,我得到了undefined. 另外,当我尝试映射数据时,我收到错误:

未处理的运行时错误

错误:无法读取未定义的属性(读取“地图”)

这是我Index.js完成数据获取的文件:

import React from 'react'

export default function Index ({data}) {
  console.log(data)
  return (
    <div>
      <main>
        <h1>Available Campaigns</h1>
        {data.map((element) => <div key={element.slug}>
          <div>
            <div>
              <img src={element.logo} height={120} width={100} alt="image" />
            </div>
            <div></div>
          </div>

        </div>)}
      </main>
    </div>
  );
}

export async function getStaticProps() {
  const response = await fetch("http://127.0.0.1:8000/api/campaigns");
  const data = await response.json();
  return {
    props: …
Run Code Online (Sandbox Code Playgroud)

javascript django rest reactjs next.js

17
推荐指数
2
解决办法
1万
查看次数

是否可以在应用程序目录内的客户端组件上使用 getServerSideProps ?

所以基本上我想在应用程序目录中的客户端组件上使用 getServerSideProps

"use client";
import React, { useLayoutEffect, useState } from "react";
import VoxelDog from "../src/components/loaders/voxel-dog";
import FirstSection from "../src/components/reusable/FirstSection";
import FeaturesSection from "../src/components/reusable/FeaturesSection";
import BannerMobile from "../src/components/mobile/BannerMobile";

// get server side props from the server

const page = (
  props: any // get the props from the server
) => {
  const [windowWidth, setWindowWidth] = useState(window.innerWidth as number);

  useLayoutEffect(() => {
    function updateSize() {
      setWindowWidth(window.innerWidth);
    }
    window.addEventListener("resize", updateSize);
    updateSize();
    return () => window.removeEventListener("resize", updateSize);
  }, [windowWidth]);

  console.log(props.data);

  return ( …
Run Code Online (Sandbox Code Playgroud)

reactjs server-side-rendering next.js

5
推荐指数
1
解决办法
8020
查看次数