javascript Next.js:带状态的 Router.push
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/55182529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Next.js: Router.push with state
提问by DaFunkyAlex
I'm using next.js for rebuilding an app for server side rendering. I have a button that handles a search request.
我正在使用 next.js 为服务器端渲染重建应用程序。我有一个处理搜索请求的按钮。
In the old app, the handler was this one:
在旧的应用程序中,处理程序是这样的:
search = (event) => {
event.preventDefault();
history.push({
pathname: '/results',
state: {
pattern: this.state.searchText,
}
});
}
In the results class, I could get the state date with this.props.location.state.pattern.
在结果类中,我可以使用 this.props.location.state.pattern 获取状态日期。
So now I'm using next.js:
所以现在我正在使用 next.js:
import Router, { withRouter } from 'next/router'
performSearch = (event) => {
event.preventDefault();
Router.push({ pathname: '/results', state: { pattern: this.state.searchText } });
};
In the results class, I use
在结果类中,我使用
static async getInitialProps({req}) {
return req.params;
}
I'm not sure if I have to add this to my server.js:
我不确定是否必须将它添加到我的 server.js 中:
server.get('/results', (req, res) => {
return app.render(req, res, '/results', req.params)
})
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?
但是,函数 getInitialProps 会抛出错误,因为 req 未定义。长文本,短问题:如何在不使用 GET 参数的情况下将状态或参数传递到另一个页面?
回答by Prithwee Das
In next.jsyou can pass query parameters like this
在next.js你可以通过这样的查询参数
Router.push({
pathname: '/about',
query: { name: 'Someone' }
})
and then in your next page (here in /aboutpage), retrieve the queryvia the routerprops, which needs to be injected to Componentby using withRouter.
然后在您的下一个页面(此处在/about页面中)中,query通过router道具检索,需要Component使用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)

