首页 > 解决方案 > 反应路由器 - 正确使用嵌套路由中的链接

问题描述

我正在尝试创建一个博客提要,当用户单击任何博客文章时,路由会更改为仅显示单个文章+标题。这使用了一些带有 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组件中呈现适当的路线?

标签: reactjsreact-routerreact-router-v4

解决方案


/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>
      </>
    );
  }
}

推荐阅读