Next.js:带有状态的Router.push

我正在使用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)

})

但是,由于未定义req,因此函数getInitialProps引发错误。长文本,简短问题:如何在不使用GET参数的情况下将状态或参数传递给另一个页面?

回答:

next.js你可以通过这样的查询参数

Router.push({

pathname: '/about',

query: { name: 'Someone' }

})

然后在你的下一个页面(在此/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)

以上是 Next.js:带有状态的Router.push 的全部内容, 来源链接: utcz.com/qa/426612.html

回到顶部