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)
})

但是,函数 getInitialProps 会抛出错误,因为 req 未定义。长文短问:如何在不使用 GET 参数的情况下将状态或参数传递到另一个页面?

原文由 DaFunkyAlex 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 848
2 个回答

next.js 你可以像这样传递查询参数

Router.push({
    pathname: '/about',
    query: { name: 'Someone' }
})

and then in your next page (here in /about page), retrieve the query via the router props, which needs to be injected to 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)

原文由 Prithwee Das 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您希望您的网址保持干净,请像下面这样对 Prithwee Das 的回答进行少量补充。

 Router.push({
    pathname: '/about',
    query: { name: 'Someone' }
}, '/about');

现在您可以使用 props 访问组件中的 props

 ...

const YourComponent = (props) => {
    useEffect(() => {
        console.log(props.router.query.name);
    }, [props.router.query]);

    return (
        <React.Fragment>
            ...
        </React.Fragment>
    );
};

...

原文由 Ahmet Firat Keler 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题