本文介绍了在组件中使用 getStaticProps的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 nextjs 和 typescript 开始了一个项目.我有一个主要组件,我在 index.js 页面中调用它我在主要组件中使用 getStaticProps 函数 getStaticProps 返回一个道具,当我在我的主要组件中记录道具时,我收到了 undifined我的控制台.我想知道使用 getStaticProps 是否错误,我必须在页面中使用该功能.我是下一个 js 的新手,如果有人能帮助我,我将不胜感激.

这是我的主要组件

import React from 'react';从../../../../interfaces/components/IMenu/IMain"导入{IMain};const Main:React.FC=(道具)=>{控制台日志(道具);返回 (

</div>);};导出异步函数 getServerSideProps() {返回 {道具: {数据:'gg'}};}导出默认 Main;

这是我的 index.js 页面

import Text from "./../components/ui/Text/Text";从../components/ui/Button/Button"导入按钮;从../components/Menu/Desktop/Main/Main"导入 Main;const Home = () =>{返回 <Main/>;};导出默认首页;

解决方案

getStaticProps 只能从页面导出.不能从非页面文件中导出.如果将getStaticProps添加为页面组件的属性,将无法使用.

https://nextjs.org/docs/basic-features/data-fetching#only-allowed-in-a-page

i started a project with nextjs and typescript.i have a main component that i call it in index.js page i use getStaticProps function in main componet getStaticProps return a props and when i log props in my main component i recieved undifined in my console.i want to know if using the getStaticProps is wrong and I have to just use that function in pages or not.i am newbie in next js and I would be very grateful if anyone could help me.

this is my main component

import React from 'react';
import {IMain} from "../../../../interfaces/components/IMenu/IMain";

const Main:React.FC<IMain> = (props) => {
    console.log(props);
    return (
        <div>
        </div>
    );
};


export async function getServerSideProps() {
    return {
        props: {
            data: 'gg'
        }
    };
}

export default Main;

and this is my index.js page

import Text from "./../components/ui/Text/Text";
import Button from "../components/ui/Button/Button";
import Main from "../components/Menu/Desktop/Main/Main";

const Home = () => {
  return <Main/>;
};




export default Home;

解决方案

getStaticProps can only be exported from a page. You can’t export it from non-page files.It will not work if you add getStaticProps as a property of the page component.

https://nextjs.org/docs/basic-features/data-fetching#only-allowed-in-a-page

这篇关于在组件中使用 getStaticProps的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 09:42