reactjs - 动态路由问题
问题描述
因为我是 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
解决方案
如果有人点击我的帖子的标题,它会将他们带到一个包含相同标题和正文的新页面
您的意思是根据用户单击的参数从 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>
如果示例不起作用,您需要将其与withRouter
from结合使用,next/router
以从 Router 对象访问您的查询。
完整示例:这里
推荐阅读
- javascript - How to clone an object with an arrow function in JavaScript?
- vuejs2 - How to deploy a vue project?
- javascript - angularjs ng-click 不适用于动态 html 元素
- python - 如何在 Python 中抑制 Keras 日志
- apache-spark - How to create spark datasets from a file without using File reader
- html - 在移动设备上播放多个视频(数据保存?)
- android - 如何从 Volley 响应中获取 JSON 值?
- python - random.shuffle(range(10)) 报告 TypeError
- string - Perl 程序从十六进制值打印 Unicode
- javascript - 如何关闭 selectize.js 选择列表中的选项列表?