我在这里遇到了一个小问题,而且很新 React 和 Redux 。我不希望我的应用上的用户有权访问其他用户个人资料。
目前我可以在URL中输入用户ID并在我登录时从用户个人资料切换到用户个人资料。
我想授予用户仅访问他/她的页面的权限。我设置了一些反应路由,以防止用户在登录后访问登录和注册页面,也可以在注销时访问配置文件页面。
是否有一种方法可以使用react路由来限制用户只能访问与其用户ID关联的页面?
App.jsx
import React from 'react';
import { Route } from 'react-router-dom';
import GreetingContainer from './session/greeting_container';
import SessionFormContainer from './session/session_form_container';
import { AuthRoute, ProtectedRoute } from '../util/route_util';
import RootRenderContainer from './session/root_render_container';
import LeaderboardContainer from './user/leaderboard_container';
import UserShowContainer from './user/user_show_container';
import ExerciseIndexContainer from './exercise/exercise_index_container';
const App = () => (
<div>
<header>
<GreetingContainer />
</header>
<ProtectedRoute exact path='/' component={RootRenderContainer}/>
<AuthRoute path="/login" component={SessionFormContainer} />
<AuthRoute path="/signup" component={SessionFormContainer} />
<Route path='/workouts' component={LeaderboardContainer} />
<Route path='/users/:userId' component={UserShowContainer} />
<Route path='/exercises' component={ExerciseIndexContainer} />
</div>
);
export default App;
受保护和身份验证路由实用程序。
import React from 'react';
import { connect } from 'react-redux';
import { withRouter, Route, Redirect } from 'react-router-dom';
const Auth = ({component: Component, path, loggedIn}) => (
<Route path={path} render={(props) => (
!loggedIn ? (
<Component {...props} />
) : (
<Redirect to="/" />
)
)}/>
);
const mapStateToProps = state => {
return {loggedIn: Boolean(state.session.currentUser),
currentUser: state.session.currentUser
};
};
export const AuthRoute = withRouter(connect(mapStateToProps, null)(Auth));
const Protected = ({component: Component, path, loggedIn, currentUser}) => (
<Route exact path={path} render={(props) => (
!loggedIn ? (
<Component {...props} />
) : (
<Redirect to={`/users/${currentUser.id}`} />
)
)}/>
);
export const ProtectedRoute = withRouter(connect(mapStateToProps, null)(Protected));