我正在尝试使用react-router进行404路由,但这不起作用。
我尝试了<Route path="*" component={PageNotFound} />
和<Route component={PageNotFound} />
,并用<Switch></Switch
包裹了我的所有路线。
我的猜测是它不起作用,因为我有两个相互嵌套的<Switch />
组件。
class App extends Component {
render() {
return (
<Provider store={store}>
<Router>
<div className="App">
<Header />
<Switch>
<Route exact path="/" component={Landing} />
<Route exact path="/login" component={Login} />
<Route exact path="/register" component={Register} />
<Route exact path="/profiles" component={Profiles} />
<Route exact path="/profile/:id" component={Profile} />
<Switch>
<PrivateRoute exact path="/dashboard" component={Dashboard} />
</Switch>
<Switch>
<PrivateRoute exact path="/posts" component={Posts} />
</Switch>
<Switch>
<PrivateRoute exact path="/post/:id" component={Post} />
</Switch>
<Switch>
<PrivateRoute
exact
path="/create-profile"
component={CreateProfile}
/>
</Switch>
<Switch>
<PrivateRoute
exact
path="/edit-profile"
component={EditProfile}
/>
</Switch>
<Route path="*" component={PageNotFound} />
</Switch>
<Footer />
</div>
</Router>
</Provider>
);
}
}
const PrivateRoute = ({ component: Component, auth, ...rest }) => (
<Route
{...rest}
render={props =>
auth.isAuthenticated === true ? (
<Component {...props} />
) : (
<Redirect to="/login" />
)
}
/>
);
我还尝试将404路由放在第一个<PrivateRoute />
的上方。它适用于非私有路由,但我希望它适用于所有路由。
上面的示例还弄乱了<PrivateRoute exact path="/posts" component={Posts} />
路由。
答案 0 :(得分:1)
我认为问题在于您拥有Switch
个区块。理想情况下,您应该拥有一个。
由于每条路线都是exact
,因此您可以将Switch
组件子节点浓缩为
class App extends Component {
render() {
return (
<Provider store={store}>
<Router>
<div className="App">
<Header />
<Switch>
<Route exact path="/" component={Landing} />
<Route exact path="/login" component={Login} />
<Route exact path="/register" component={Register} />
<Route exact path="/profiles" component={Profiles} />
<Route exact path="/profile/:id" component={Profile} />
<PrivateRoute exact path="/dashboard" component={Dashboard} />
<PrivateRoute exact path="/posts" component={Posts} />
<PrivateRoute exact path="/post/:id" component={Post} />
<PrivateRoute
exact
path="/create-profile"
component={CreateProfile}
/>
<PrivateRoute
exact
path="/edit-profile"
component={EditProfile}
/>
<Route component={PageNotFound} />
</Switch>
<Footer />
</div>
</Router>
</Provider>
);
}
}
如果在整个Switch
块中没有路由匹配,这将使404页成为一个包罗万象的东西。