Next.js:带有状态的Router.push [英] Next.js: Router.push with state
问题描述
我正在使用next.js重建用于服务器端渲染的应用程序. 我有一个用于处理搜索请求的按钮.
I'm using next.js for rebuilding an app for server side rendering. I have a button that handles a search request.
在旧版应用中,处理程序是这样的:
In the old app, the handler was this one:
search = (event) => {
event.preventDefault();
history.push({
pathname: '/results',
state: {
pattern: this.state.searchText,
}
});
}
在结果类中,我可以使用this.props.location.state.pattern获取状态日期.
In the results class, I could get the state date with this.props.location.state.pattern.
所以现在我正在使用next.js:
So now I'm using next.js:
import Router, { withRouter } from 'next/router'
performSearch = (event) => {
event.preventDefault();
Router.push({ pathname: '/results', state: { pattern: this.state.searchText } });
};
在结果类中,我使用
static async getInitialProps({req}) {
return req.params;
}
我不确定是否必须将其添加到我的server.js:
I'm not sure if I have to add this to my server.js:
server.get('/results', (req, res) => {
return app.render(req, res, '/results', req.params)
})
但是,由于req是未定义的,因此函数getInitialProps会引发错误.长文本,简短问题:如何在不使用GET参数的情况下将状态或参数传递给另一个页面?
However, the function getInitialProps throws an error because req is undefined. Long text, short question: how to pass state or params to another page without using GET parameters?
推荐答案
在next.js
中,您可以传递这样的查询参数
In next.js
you can pass query parameters like this
Router.push({
pathname: '/about',
query: { name: 'Someone' }
})
,然后在下一页(此处为/about
页)中,通过router
道具检索query
,需要使用withRouter
将其注入到Component
.
and then in your next page (here in /about
page), retrieve the query
via the router
props, which needs to be injected to Component
by using withRouter
.
import { withRouter } from 'next/router'
class About extends React.Component {
// your Component implementation
// retrieve them like this
// this.props.router.query.name
}
export default withRouter(About)
这篇关于Next.js:带有状态的Router.push的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!