我对动态路由有点困惑,因为我是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发布于 2020-03-03 12:35:25
如果有人点击我帖子的标题,它会把他们带到一个包含相同标题和正文的新页面
你的意思是标题和正文是根据用户点击的参数从MongoDB获取的吗?
如果是,由于您使用的是ExpressJS,您可以在Github上查看他们的示例:
server.get('/posts/:id', (req, res) => {
return app.render(req, res, '/posts', { id: req.params.id })
})有一个/posts/:id接口,它基本上满足了你想要实现的目标。其思想是从用户的请求中获取唯一的参数,然后将该参数转发到您的特定页面,并根据用户的参数调用接口来获取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>如果该示例不起作用,您需要将其与来自next/router的withRouter组合,以便从路由器对象访问您的查询。
完整示例:here
https://stackoverflow.com/questions/60497192
复制相似问题