反应路由器-正确使用嵌套路由内的链接

时间:2018-11-02 15:07:54

标签: reactjs react-router react-router-v4

我正在尝试提供一个博客供稿,当用户单击任何博客帖子时,路由会更改为仅显示单个帖子+标题。这使用了一些带有react-router的嵌套路由,所有tutorials都展示了如何在嵌套的更深处显示动态数据,而不是如何覆盖父路由。

博客组件:

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

index.jsx

// renders all of react
ReactDOM.render(
  <Router>
    <Route path="/" component={Blog} />
  </Router>,
  document.getElementById('root')
);

CodeSandbox

我遇到的问题是Feed可以正常工作,并且所有Post链接都可以正常工作。当我单击任何帖子时,react不知道我要访问哪个Post

这是我不确定如何进行的地方,因为我发现的所有教程都只显示了Post组件嵌套的位置。如何判断我要查看的帖子,并使其在Blog组件中呈现适当的路线?

1 个答案:

答案 0 :(得分:0)

您的代码运行良好,但是当/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>
      </>
    );
  }
}