reactjs - 反应路由器 - 正确使用嵌套路由中的链接
问题描述
我正在尝试创建一个博客提要,当用户单击任何博客文章时,路由会更改为仅显示单个文章+标题。这使用了一些带有 react-router 的嵌套路由,所有教程都展示了如何在嵌套的下方显示动态数据,而不是如何覆盖父路由。
博客组件:
class Blog extends React.Component {
constructor(props) {
super(props);
}
render() {
const posts = [
{ id: 1, title: "Post 1", slug: "post-1" },
{ id: 2, title: "Post 2", slug: "post-2" },
{ id: 3, title: "Post 3", slug: "post-3" }
];
return (
<>
<Header />
<Route
exact
path="/"
render={() => (
<>
<SidebarLeft />
<Feed />
<SidebarRight />
</>
)}
/>
{/* I need to somehow pass the postTitle & postSlug props by only having access to the slug url param */}
<Route path="/articles/:postSlug" component={Post} />
</>
);
}
}
饲料成分:
class Feed extends React.Component {
constructor(props) {
super(props);
}
render() {
// gets posts from props
var jsonPosts = this.props.posts;
var arr = [];
Object.keys(jsonPosts).forEach(function(key) {
arr.push(jsonPosts[key]);
});
return (
<>
{arr.map(post => (
<Post
key={post.id}
postSlug={post.slug}
postTitle={post.title}
/>
))}
</>
);
}
}
帖子组件:
class Post extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<h1>{this.props.postTitle}</h1>
<Link to={'/articles/' + this.props.postSlug}>{this.props.postSlug}</Link>
);
}
}
索引.jsx
// renders all of react
ReactDOM.render(
<Router>
<Route path="/" component={Blog} />
</Router>,
document.getElementById('root')
);
我遇到的问题是Feed
工作正常,所有Post
链接都有效。当我点击任何帖子时,react 不知道Post
我要访问哪个帖子。
这是我不确定如何继续的地方,因为我发现的所有教程都只是显示Post
嵌套更深的组件。我如何告诉 react 我正在尝试查看哪个帖子并让它在Blog
组件中呈现适当的路线?
解决方案
/articles/:postSlug
您的代码运行良好,但您必须添加一些额外的逻辑才能在匹配
时传递正确的道具。
例子
class Blog extends React.Component {
render() {
const posts = [
{ id: 1, title: "Post 1", slug: "post-1" },
{ id: 2, title: "Post 2", slug: "post-2" },
{ id: 3, title: "Post 3", slug: "post-3" }
];
return (
<>
<Header />
<Switch>
<Route
exact
path="/"
render={() => (
<Feed posts={posts} />
)}
/>
<Route
path="/articles/:postSlug"
render={props => {
const post = posts.find(p => p.slug === props.match.params.postSlug);
if (!post) {
return null;
}
return <Post {...props} postTitle={post.title} postSlug={post.slug} />;
}}
/>
</Switch>
</>
);
}
}
推荐阅读
- c# - PrincipalContext.ValidateCredentials 对某些用户失败?
- python - Logistic 回归中已超过最大迭代次数
- java - 我正在搜索用于清除后台运行的应用程序并从最近的应用程序菜单中删除所有其他应用程序的代码
- javascript - 依赖项的错误无法解决
- angular - 如何修复 Rest Login API Symfony 4?
- mysql - 如何找到发送的消息多于收到的消息的人?
- linux - 在 tcsh 脚本中记录所有 echo 语句
- python - 如何在 Python 中将嵌套字典中的 2 个键/值向上移动一级
- python - 如何获取mongodb数组中对象的值?
- c++ - QByteArray 上的 QDataStream:在 DataStream ('<<') 上的写入之间从数组 ('[ ]') 读取是否安全?