我有两个页面使用相同的一个组件Posts
作为searchModel
道具,当我使用 Next Link 更改路径时,除非刷新页面,否则组件永远不会重新呈现。我的代码:
index.js
export default function Home({ posts, searchModel }) {
const postsProps = {
posts: posts.records,
totalCount: posts.totalCount,
searchModel
}
return <Posts {...postsProps} />
}
export async function getServerSideProps() {...}
类别/[id]/[slug].js
export default function Category({ posts, searchModel ,category,error}) {
const postsProps = {
posts: posts.records,
totalCount: posts.totalCount,
searchModel,
title: category.title
}
return <Posts {...postsProps} />
}
export async function getServerSideProps() {
try {
const { params } = context
const category = (await CategoryService.getById(params.id)).data
const searchModel = {
...Utils.getInitialSearchModel(),
categoryId: params.id
}
const posts = (await PostService.search(searchModel)).data
return { props: { posts, searchModel, category } }
} catch (error) {
return { props: { error } }
}
}
和帖子:
class Posts extends Component {
constructor(props) {
super(props);
console.log({ posts: props.posts }) // runs only once, on page load, will never hit on next link click
this.state = {
posts: props.posts,
totalCount: props.totalCount,
searchModel: props.searchModel,
}
}
componentDidMount = () =>{
console.log('component mounted') // this never hits on page change
}
// ....
有什么我做错了吗?我可以绕过它而不必使用 componentDidUpdate() 吗?