首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >NEXTJS: getServerSideProps不工作于组件

NEXTJS: getServerSideProps不工作于组件
EN

Stack Overflow用户
提问于 2020-09-30 10:50:44
回答 2查看 29.4K关注 0票数 16

下面的

是位于“Pages/ code .js”上的代码。//本地主机:3000/home

代码语言:javascript
运行
复制
    import axios from 'axios';
    import Section1 from '../components/home-sections/section-1';
    
    const Homepage = ({ show }) => {
        const Html = JSON.parse(show.response.DesktopHTML);
        const renderSection = () => {
            return Html.map((itemData,index)=>{
                return(<div key={index}>{itemData.DisplayName}</div>)
            })
        }
    
        return(
            <div>
                { renderSection()}
                <Section1 />
            </div>
        )
    }
    
    export const getServerSideProps = async ({ query }) => {
     
      try {
        const response = await axios.get(
          `https://api.example.com/getHomeSection?title=Section 1`
        );
        
        return {
          props: {
            show: response.data,
          },
        };
      } catch (error) {
        return {
          props: {
            error: error.error,
          },
        };
      }
    };
    
    export default Homepage;

现在,我添加到-1.js节中的相同代码,这个文件位于"components/home-sections/section-1.js

现在,getServerSideProps在home.js中运行得很好,但在第1.js节中,它不起作用。

代码语言:javascript
运行
复制
Error: TypeError: show is undefined in section-1.js
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-09-30 13:12:27

不能在非页面组件中使用getServerSideProps。您可以将道具从Home传递给HomeSection,也可以创建上下文,以便可以从组件树全局使用该值。

getServerSideProps只能从页面导出。您不能从非页面文件导出它。

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

票数 40
EN

Stack Overflow用户

发布于 2022-09-04 16:44:06

getServerSideProps只能从Page导出。它不会在导入到页面的组件上运行。

但是,您可以从返回道具的组件导出函数,并从页面的getServerSideProps函数调用该函数。

  1. 在组件上创建getServerSideProps函数。

// @Component.tsx从‘next’导入{ GetServerSidePropsContext };函数MyComponent(支持: IMyComponentProps) {返回(MyComponent;) } MyComponent.getServerSideProps =异步(上下文: GetServerSidePropsContext):Promise<{ props: IMyComponentProps }> => { from { props:{…}};}导出默认MyComponent;

  1. 在页面的getServerSideProps函数中,调用组件的getServerSideProps函数,并将组件中的道具与页面中的道具合并。

// mypage.tsx从‘@components/ MyComponent’导入MyComponent;const Page: NextPageWithLayout = (props: IIndexPageProps) => { return;}导出异步函数getServerSideProps(上下文: GetServerSidePropsContext):Promise<{ props: IIndexPageProps }> { let componentServerSideProps =等待MyComponent.getServerSideProps(上下文);让otherServerSideProps ={ props:{…} };返回{ props:{ ...componentServerSideProps.props,...otherServerSideProps.props } };}

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64136025

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档