我想在路线上找到一个未找到的组件
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import PropTypes from 'prop-types';
import Home from './components/home';
import MyWork from './components/work/myWork';
import WorkShow from './components/work/workShow';
import NavigationBar from './components/shared/navbar';
import Footer from './components/shared/footer';
import CategoryShow from './components/category/categoryShow';
import PostIndex from './components/post/postIndex';
import PostShow from './components/post/postShow';
import PostSearch from './components/post/postSearch';
import TagShow from './components/tag/tagShow';
import NotFound from './components/shared/notFound';
const DefaultLayout = ({ component: Component, ...rest }) => (
<Route
{...rest} render={matchProps => (
<div>
<NavigationBar />
<div className="mainContent">
<Component {...matchProps} />
</div>
<Footer />
</div>
)}
/>
);
DefaultLayout.propTypes = ({
component: PropTypes.shape.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.shape.isRequired,
});
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={Home} />
<DefaultLayout path="/my-work" component={Work} />
<BlogLayout path="/blog" component={Blog} />
</div>
);
export default routes;
我试过了:
const routes = (
<div>
<DefaultLayout exact path="/" component={Home} />
<DefaultLayout path="/my-work" component={Work} />
<BlogLayout path="/blog" component={Blog} />
<BlogLayout path="*" component={NotFound} />
</div>
);
但NotFound组件总是渲染,我只想在用户输入错误的URL时进行渲染。我如何在反应路由器v4中执行此操作?
答案 0 :(得分:0)
这不是有效的路由器反应块:
const routes = (
<div>
<DefaultLayout exact path="/" component={Home} />
<DefaultLayout path="/my-work" component={Work} />
<BlogLayout path="/blog" component={Blog} />
</div>
);
您需要实际使用路由和交换机等React组件(就像您在组件本身中所做的那样)。类似的东西:
<Switch>
<Route exact path='/' component={Home}/>
<Route path='/my-work' component={Work}/>
<Route path='/blog' component={Blog}/>
</Switch>
答案 1 :(得分:0)
您只需要使用没有路径属性的Switch和Route。
const routes = (
<Switch>
<Route exact path="/" component={Home} />
<Route path="/my-work" component={Work} />
<Route path="/blog" component={Blog} />
<Route component={NotFound} />
<Switch>
);