NEXTJS:getServerSideProps不能用于组件 [英] NEXTJS: getServerSideProps not working into components
本文介绍了NEXTJS:getServerSideProps不能用于组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是位于";ages/home.js";的代码。//localhost: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
推荐答案
不能在非页面组件中使用getServerSideProps
。您可以将属性从Home
传递到HomeSection
,也可以创建上下文,以便可以从组件树全局使用该值
getServerSideProps只能从页面导出。你不能出口 它来自非页面文件。
https://nextjs.org/docs/basic-features/data-fetching#only-allowed-in-a-page-2
这篇关于NEXTJS:getServerSideProps不能用于组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文