简体   繁体   English

用于服务器端渲染的 Next.js 路由器中的匹配和参数对象

[英]Match and Param object in Next.js router for Server side rendering

I am trying to convert my client side application to server side rendered because of problem in SEO.由于 SEO 中的问题,我正在尝试将我的客户端应用程序转换为服务器端呈现。 For client side I have used react router which is passing the prop to other child components while render.对于客户端,我使用了反应路由器,它在渲染时将道具传递给其他子组件。

Below is current code以下是当前代码

App.js应用程序.js

render() {
return (
<Switch>
<Route path={constant.pathId + constant.pathGender} render={(props) => <HomeScreen {...props} />} />
</Switch>
);
}

Const常量

export const industryRegexGender = "(men||women)";
export const industryRegex = "(en-kw||en-qa||en-ae||en-bh||en-om||en-sa||ar-kw||ar-qa||ar-ae||ar-bh||ar-om||ar-sa)";
export const pathId = `/:id${industryRegex}`;
export const pathGender = `/:gender${industryRegexGender}`;

Homescreen component ( Getting the value here in the child components)主屏幕组件(在子组件中获取此处的值)

let paramId = this.props.match.params.id

Screenshot of console控制台截图

在此处输入图片说明

I am not sure how to achieve this with Next/router, already tried following next.js documentation.我不确定如何使用 Next/router 实现这一点,已经尝试遵循 next.js 文档。

Any help of sample would be really appreciated.任何样品的帮助将不胜感激。

if your component is functional component then use "useRouter" hook.如果您的组件是功能组件,则使用“useRouter”钩子。

  import { useRouter } from 'next/router'

  const Post = () => {
  const router = useRouter()
  //console.log(router) to see router object
  const { pid } = router.query
  return <p>Post: {pid}</p>}

  export default Post

if your function is class component, you use withRouter()如果您的函数是类组件,则使用 withRouter()

import { withRouter } from 'next/router'

function Page({ router }) {
  return <p>{router.pathname}</p>
}

export default withRouter(Page)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM