React Router v4路径不匹配问题

时间:2017-07-13 18:15:40

标签: reactjs react-router-v4

当我在URL中输入的路径不存在时,我正在尝试渲染404页面。

这是我的router.jsx:

const NotFoundLayout = () => (
  <div><h1>Not Found</h1></div>
);

const DefaultLayout = ({ component: Component, ...rest }) => (
  <Route
    {...rest} render={matchProps => (
      <div>
        <NavigationBar />
        <div className="mainContent">
          <Component {...matchProps} />
        </div>
        <Footer />
      </div>
    )}
  />
);

DefaultLayout.propTypes = ({
  component: PropTypes.func.isRequired,
});

const BlogLayout = ({ component: Component, ...rest }) => (
  <Route
    {...rest} render={matchProps => (
      <div>
        <NavigationBar path="blog" />
        <div className="mainContent">
          <Component {...matchProps} />
        </div>
        <Footer />
      </div>
    )}
  />
);

BlogLayout.propTypes = ({
  component: PropTypes.func.isRequired,
});

const HomePath = () => (
  <Switch>
    <Route exact path="/" component={Home} />
  </Switch>
);

const NotFoundPath = () => (
  <Switch>
    <Route component={NotFoundLayout} />
  </Switch>
);

const Work = () => (
  <Switch>
    <Route exact path="/my-work" component={MyWork} />
    <Route path="/my-work/:workName" component={WorkShow} />
  </Switch>
);

const Blog = () => (
  <Switch>
    <Route exact path="/blog" component={PostIndex} />
    <Route path="/blog/search" component={PostSearch} />
    <Route exact path="/blog/:postName" component={PostShow} />
    <Route path="/blog/category/:categoryName" component={CategoryShow} />
    <Route path="/blog/tag/:tagName" component={TagShow} />
  </Switch>
);

const routes = (
  <div>
    <DefaultLayout exact path="/" component={HomePath} />
    <DefaultLayout path="/my-work" component={Work} />
    <BlogLayout path="/blog" component={Blog} />
    <DefaultLayout component={NotFoundPath} />
  </div>
);

export default routes;

NotFoundLayout显示在每个组件的底部。如何更改此文件以便仅在路径不匹配时显示?

1 个答案:

答案 0 :(得分:2)

您应该使用<Switch>中的routes组件,就像您在BlogWork和其他人中所做的那样