我在用next.js用于重建用于服务器端渲染的应用程序.

在旧应用程序中,处理程序是这样的:

search = (event) => {
    event.preventDefault();
    history.push({
        pathname: '/results',
        state: {
            pattern: this.state.searchText,
        }
    });
}

在结果课上,我可以用这个得到州日期.props .地方状态图案

所以现在我用下一个.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;
}

我不确定是否必须将其添加到我的服务器.js:

server.get('/results', (req, res) => {
    return app.render(req, res, '/results', req.params)
})

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

推荐答案

next.js中,您可以像这样传递查询参数

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

然后在你的下一页(这里是/about页),通过routerprops 检索queryprops ,这需要通过withRouter注入Componentprops .

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)

Reactjs相关问答推荐

如何使数据库数据在第一次呈现时显示?

在新屏幕上显示照片时出现问题-react

如何使ionic 面包屑在州政府条件下可点击?

Antd V5组件自定义主题

错误:操作必须是普通对象.使用自定义中间件进行异步操作. Redux/工具包

useMemo 依赖项的行为

使用D3.js绘制和展示弦图的右下方象限

ReactJS中使用setState方法时,Context内部的State未进行更新

React Router v6 路径中的符号

在按钮单击中将动态参数传递给 React Query

表单错误后 Ionic React 无法 Select 单选按钮

null 不是对象(判断RNSound.IsAndroid)

useState 在生命周期中的位置

react-markdown 不渲染 Markdown

如何解决在 react.js 中找不到模块错误

如何修复 Next.js 13 中类型 AppRouterInstance 上不存在 x?

如何使用 useEffect 和 if 语句 React

我可以在类组件中使用 useState 挂钩吗?

react-three-fiber 场景背景比原图更亮

从 React 中的sibling 组件刷新组件