getServerSideProps 在映射中的 nextjs 错误中不起作用

getServerSideProps not working in nextjs error in mapping

我正在尝试执行 getServerSideProps,但出现以下错误我正在执行的错误是什么

TypeError: Cannot read properties of undefined (reading 'map')

import React from "react";
import axios from "axios";
import { useState, useEffect } from "react";
import { FormControl, Button } from "react-bootstrap";
import Card from "react-bootstrap/Card";

export default function Answershooks(props, { posts }) {


  return (
    <div className="answerhook">
       {posts.map((personData, index) => {
        return (
          <Card key={index} className="cardmobile">
            <Card.Body>
              <p className="answersize">{personData.Answers} </p>
            </Card.Body>
          </Card>
         );
      })}
    </div>
  );
}
export async function getServerSideProps(ctx) {
  
  const res = await fetch("https://askover.wixten.com/answersapi/" + props.id);
  console.log(res);
  console.log("dada");
  const posts = await res.json();

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  };
}

我添加了一个文件结构截图,这样你就能理解我的文件是如何放置的

让我们从提取错误开始,找出失败的原因,然后创建一个新组件。

fetchHandler.js

export async function fetchHandler(url){
  try{
      const res = await fetch(url);
      return res
  } catch(err){
      console.log(err); //this will tell us why it failed.
      return false //this gives us a condition we can use on the front end
    } 
}

然后是你的 Answerhooks。

import {fetchHandler} from '../yourpath'

export default function Answershooks({ posts }) {


  return (
    <div className="answerhook">
       {posts.map((personData, index) => {
        return (
          <Card key={index} className="cardmobile">
            <Card.Body>
              <p className="answersize">{personData.Answers} </p>
            </Card.Body>
          </Card>
         );
      })}
    </div>
  );
}
export async function getServerSideProps(ctx) {

  const url = `https://askover.wixten.com/answersapi/${ctx.query.id}`
  const res = await fetchHandler(url)
  console.log(res);
  const posts = await res.json();

  return {
    props: {
      posts: posts === false ? [] : posts //Just to stop your app crashing
    },
  };
}

您的主要问题是您试图在 Answerhooks 中调用 getServerSideProps 但它不是页面组件,因此您无法按预期在服务器上获取数据

您可以将 API 调用移动到 [itmid].jsx 中的 getServerSideProps(这是一个实际的页面组件),而不是 getServerSideProps,如下所示

export async function getServerSideProps(ctx) {
  var id = ctx.query.itmid;

  const queryRequest = fetch("https://ask-over.herokuapp.com/questone/" + id).then(async (res) => await res.json());
  const answerRequest = fetch("https://askover.wixten.com/answersapi/" + id).then(async (res) => await res.json());
  const [posts, answerPosts] = await Promise.all([queryRequest, answerRequest]);

  return {
    props: {
      posts,
      answerPosts
    }
  };
}

之后,你可以从Query

的道具中获得answerPosts
function Query({ posts, answerPosts }) {
   return <Answerhooks answerPosts={answerPosts} />
}

最后,你可以在Answerhooks组件

中获取props的数据
function Answershooks({ answerPosts }) {
   
   //TODO: Apply your logic with `answerPosts`
   console.log(answerPosts)

   return <div></div>
}

我认为问题出在您的获取方法中的 props.id,因为您无法访问必须在页面中调用的 getServersideProps 中的道具。您应该尝试从 url 中获取 ID,例如 http://.....?id=your-id

然后在getServerSideProps

export async function getServerSideProps(ctx) {
  
const res = await fetch(`https://askover.wixten.com/answersapi/${ctx.query.id}`);
console.log(res);
const posts = await res.json();

return {
  props: {
    posts,
  },
};

}

export const getServerSideProps = wrapper.getServerSideProps(
    (store) =>
        async ({req}) => {

         const result =  await store.dispatch(fetchHome());

            return {
                props: {
                    list : result
                },
            };
        }
);