{...rest}
应该不包括 path
,但是还是能正常跳转,这是为什么<ProtectedRoute path="/movies/:id" component={MovieForm} />
const ProtectedRoute = ({ path, component: Component, render, ...rest }) => {
console.log("rest: ", { ...rest });
return (
<Route
// path={path}
{...rest}
render={(props) => {
console.log(props);
if (!auth.getCutterntUser()) return <Redirect to="/login" />;
return Component ? <Component {...props} /> : render(props);
}}
/>
);
};
<Switch>
<Route path="/register" component={RegisterForm}></Route>
<Route path="/login" component={LoginForm}></Route>
<Route path="/logout" component={Logout}></Route>
<Route path="/movies/1" render={() => <h1>test</h1>} />
<ProtectedRoute path="/movies/:id" component={MovieForm} />
<Route
path="/movies"
render={(props) => <Movies {...props} user={this.state.user} />}
></Route>
<Route path="/customers" component={Customers}></Route>
<Route path="/rentals" component={Rentals}></Route>
<Route path="/not-found" component={NotFound}></Route>
<Redirect from="/" exact to="/movies" />
<Redirect to="/not-found" />
</Switch>
我现在是一个不使用 Switch标签的情况,不论我是否写入了匹配路由都会呈现在页面上
如果使用了 Switch 标签进行包裹
刚刚查阅了几遍博客 总结了一下
https://segmentfault.com/a/1190000022665185
https://zhuanlan.zhihu.com/p/142486396
Switch 的原理是对子组件,也就是 Route 组件从上到下遍历,找到第一个匹配的组件。使用 React.cloneElement 将其返回,更新其中的 computedMatch 为 true, Route 组件读到这个属性后,就知道匹配路径的事情被 Switch 干了,自己的展示组件就好了。
简单的说 会抓取子组件的内容 而 Switch 的第一顺位子组件是 ProtectedRoute 抓取的其实是这个组件,也就是根据源码
抓到了 ProtectedRoute 的path 进行了绑定,测试一下将 ProtectedRoute 组件的 path 更改成 path1 效果如下
这个时候就不会在匹配了
你确定是跳转了? url路径变了? 还是只是 也能渲染内容
你如果没有path的话默认情况下是会呈现在页面上的,也就是没有匹配规则的一个路由,正常情况下来说是会直接呈现在页面上的,推荐你可以随意输入一个路由,看一下是否这个路由会呈现在页面上,当然也不排除你在项目的其他位置写了判断,然后追一下错误,到底是什么原因。