我创建了简单的应用程序,我通过数值menuApi.js到[catId].js,之后不能通过catId值是26(即http://localhost:3000/category/26,现在我通过getServersideProps方法内的catId但不工作。我错过了什么。
menuApi.js
import React, { Component } from 'react';
import { Grid, Image } from "semantic-ui-react";
import Link from 'next/link';
function MenuApi(props) {
return (
<Grid className="home-icon">
<Grid.Row centered doubling columns={8} mobile>
{props.menu.map((x, i) => (
<Grid.Column centered key={i} Style="width: 9%!important;">
<Link
href={'/category/'+x.id}
>
<Image src={x.image} alt=""/>
</Link>
<Link href={x.category_url}>
<p >{x.store_name}</p>
</Link>
</Grid.Column>
))}
</Grid.Row>
</Grid>
)
}
export default MenuApi;
(catId) . js
import { useRouter } from 'next/router'
const Post = (props) => {
console.log(props.ruslt)
return <p>Post: {storeId}</p>
}
const router = useRouter()
const { storeId } = router.query
export async function getServerSideProps(context) {
const offerList = await fetch('http://localhost:3000/api/v4/web/list',{
method:'POST',
body: JSON.stringify(storeId),
headers: { "Content-Type": "application/json" },
})
const offerData = await offerList.json();
const result=offerData.stores;
return {
props: {
result,
},
};
}
export default Post
您在功能组件之外使用useRouter
钩子。Hooks只能在功能组件中使用,而不能在getServerSideProps
中使用。
应该是这样的:
const Post = (props) => {
const router = useRouter()
const { storeId } = router.query
console.log(props.result)
return <p>Post: {storeId}</p>
}
另外,您应该使用getStaticProps
而不是getServerSideProps
。getServerSideProps
将在每个请求时呈现页面,因此您的响应时间将增加。
使用getStaticProps
,它会预先渲染你的页面,这样响应时间就会减少。
Next中的数据提取
下面的代码应该可以修复它。你似乎从getServerSideProps
函数传递错误的道具
import { useRouter } from 'next/router'
const Post = (props) => {
console.log(props.result)
return <p>Post: {props.storeId}</p>
}
const router = useRouter()
const { storeId } = router.query
export async function getServerSideProps(context) {
const offerList = await fetch('http://localhost:3000/api/v4/web/list',{
method:'POST',
body: storeId,
headers: { "Content-Type": "application/json" },
})
const offerData = offerList;
const result=offerData.stores;
return {
props: {
result,
storeId
},
};
}
export default Post