首页 > 解决方案 > 如何在 ReactJS 中的模糊路由中停止第一次匹配时的路由器匹配

问题描述

在我的项目中,我有不同页面的路线。我想在第一条路线匹配时停止执行。我的 route.js 文件有这个代码

export default [
    {
        exact: true,
        component: Home,
        path: "/"
    },
    {
        exact: true,
        component: ShopingCart,
        path: "/shopingcart"
    },
    {
        exact: true,
        component: LinkChanger,
        path: "/:pathname"
    }
];

我有一个使用这些 route.js 文件的文件

<Switch>
    <Router  history={history} >
        <div>
        {
             routes.map( (route, index) =>
             <Route key={index} exact={route.exact} path={route.path} component={(props)=><route.component {...props} isAuthed={true} />}/>)
        }
        </div>
    </Router>
</Switch>

当我将链接更改为 /shopingcart 时。首先调用组件 ShopingCart,然后调用 LinkChanger。即使在使用 switch 之后,我的第二个组件 LinkChanger 也会被调用。他们有什么方法可以在第一次比赛时阻止路由器。

标签: reactjsreact-nativereact-reduxreact-router

解决方案


尝试包裹Switch在里面Router-

<Router history={history}>
    <Switch>
        {
            routes.map( (route, index) =>
            <Route key={index} exact={route.exact} path={route.path} component={(props)=><route.component {...props} isAuthed={true} />}/>)
        }
    </Switch>
</Router>

推荐阅读