下面的
是位于“Pages/ code .js”上的代码。//本地主机:3000/home
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节中,它不起作用。
Error: TypeError: show is undefined in section-1.js
发布于 2020-09-30 13:12:27
不能在非页面组件中使用getServerSideProps
。您可以将道具从Home
传递给HomeSection
,也可以创建上下文,以便可以从组件树全局使用该值。
getServerSideProps只能从页面导出。您不能从非页面文件导出它。
https://nextjs.org/docs/basic-features/data-fetching#only-allowed-in-a-page-2
发布于 2022-09-04 16:44:06
getServerSideProps
只能从Page导出。它不会在导入到页面的组件上运行。
但是,您可以从返回道具的组件导出函数,并从页面的getServerSideProps
函数调用该函数。
getServerSideProps
函数。// @Component.tsx从‘next’导入{ GetServerSidePropsContext };函数MyComponent(支持: IMyComponentProps) {返回(MyComponent;) } MyComponent.getServerSideProps =异步(上下文: GetServerSidePropsContext):Promise<{ props: IMyComponentProps }> => { from { props:{…}};}导出默认MyComponent;
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 } };}
https://stackoverflow.com/questions/64136025
复制相似问题