我正在使用 next.js 重建用于服务器端渲染的应用程序。我有一个处理搜索请求的按钮。
在旧应用程序中,处理程序是这个:
search = (event) => {
event.preventDefault();
history.push({
pathname: '/results',
state: {
pattern: this.state.searchText,
}
});
}
在结果类中,我可以使用 this.props.location.state.pattern 获取状态日期。
所以现在我正在使用 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 中:
server.get('/results', (req, res) => {
return app.render(req, res, '/results', req.params)
})
但是,函数 getInitialProps 会抛出错误,因为 req 未定义。长文短问:如何在不使用 GET 参数的情况下将状态或参数传递到另一个页面?
原文由 DaFunkyAlex 发布,翻译遵循 CC BY-SA 4.0 许可协议
在
next.js
你可以像这样传递查询参数and then in your next page (here in
/about
page), retrieve thequery
via therouter
props, which needs to be injected toComponent
通过使用withRouter
。