首页 > 解决方案 > 动态路由问题

问题描述

因为我是 NextJS 的新手,所以我对动态路由有点困惑。我希望它是这样的,如果有人点击我页面的标题,它会将他们带到一个包含相同标题和正文的新页面。为了实现这一目标,我可以做出哪些改变?我检查了许多资源,但它们要么是从 a 到 b,而且数据是硬编码的。

import React from 'react';
import axios from 'axios'
import Link from 'next/link';


class Abc extends React.Component{
    state = {
        title: '',
        body: '',
        posts: []
    };

    componentDidMount=()=>{
        this.getBlogPost();
    };



displayBody=(posts: Array<any>)=>{
 if(!posts.length)
 return null;
 return posts.map((post,index)=>(
<div key={index}>

 <Link href={`/post?title=${this.state.title}`} ><a> 
 {post.title}</a></Link>
    <h2>{post.title}</h2>
    <p>{post.body}</p>

</div>
 ));

};
    render() {
        console.log('state', this.state);
        return (
            <div>
                <h2>Welcome to my app</h2>

            <div className="blog">

                {this.displayBody(this.state.posts)}
            </div>


            </div>
        );
    }
}

export default Abc

标签: reactjstypescriptnext.js

解决方案


如果有人点击我的帖子的标题,它会将他们带到一个包含相同标题和正文的新页面

您的意思是根据用户单击的参数从 MongoDB 获取标题和正文吗?

如果是,由于您使用的是 ExpressJS,您可以在 Github 上查看他们的示例:

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

有一个 API/posts/:id基本上可以满足您想要实现的目标。这个想法是从用户的请求中获取唯一的参数,然后将此参数转发到您的特定页面,并根据用户的参数调用 API 以获取到 MongoDB。

更新答案

这是pages/posts这样的:

import React, { Component } from 'react'

export default class extends Component {
  static getInitialProps({ query: { id, title, body } }) {
    return { postId: id, title, body }
  }

  render() {
    return (
      <div>
        <h1>My blog post #{this.props.postId}</h1>
        <p>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
          eiusmod tempor incididunt ut labore et dolore magna aliqua.
        </p>
      </div>
    )
  }
}

您需要做的是添加getInitialProps从服务器发送的查询中检索 id 的函数。

第二次更新答案

然后你可以使用next/link如下的对象 url:

<Link href={{ pathname: `/post?title=${this.state.title}`, query: { title: this.state.title, body: this.state.body } }}>
    <a>{post.title}</a>
</Link>

如果示例不起作用,您需要将其与withRouterfrom结合使用,next/router以从 Router 对象访问您的查询。

完整示例:这里


推荐阅读