这些是我的应用程序允许的路线:
/
/topic/development
/topic/database
/topic/security
/pages/:page (:page can only be a number)
我在访问以下内容时为用户显示Not Found
时遇到问题:
/topic/whatever
我在哪里可以指定用户允许的路由?
在<Switch/>
内有一个没有path
的组件。
<Switch>
<Route path="/" exact component={Home}/>
<Route path="/will-match" component={WillMatch}/>
... More paths here
<Route component={NoMatch}/>
</Switch>
我想你提到“允许用户使用路由?”,这意味着您的应用中存在一些身份验证层。
让我们在你的initialState中说:
{
user: undefined,
logged: false
}
你可以做的是装饰路线,以检查这个属性的状态,如:
const renderMergedProps = (component, ...rest) => {
const finalProps = Object.assign({}, ...rest);
return (
React.createElement(component, finalProps)
);
};
const PrivateRoute = ({ user, component, redirectTo, ...rest }) => {
return (
<Route {...rest} render={routeProps => {
return user.logged ? (
renderMergedProps(component, routeProps, rest)
) : (
<Redirect to={{
pathname: redirectTo,
state: { from: routeProps.location }
}} />
);
}} />
);
};
你现在可以定义路线和私人空间,传递必要的道具:
<Route exact path="/" render={() => (<Redirect to="/dashboard" />)} />
<PrivateRoute path="/dashboard" component={App} user={user} redirectTo="/login"/>
然后,对状态变化做出反应的最佳解决方案是以redux方式实现这一点。如果需要,可以更多地说明。