Next.js:带状态的 Router.push [英] Next.js: Router.push with state

查看:26
本文介绍了Next.js:带状态的 Router.push的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

但是,函数 getInitialProps 会抛出错误,因为 req 未定义.长文本,短问题:如何在不使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆