我想问是否只有在Redux状态被加载时才使路由可用是不好的做法。我正在使用MERN堆栈开发Web应用程序。前端是在React和Redux中,我正在使用JWT身份验证,我正在签入如果localStorage中有令牌,并且是否存在向服务器发送请求以检查令牌的组件,则为componentDidMount方法中的App.js(我正在使用sagas来处理异步调用)。这是App.js代码:
class App extends Component {
componentDidMount(){
console.log('app component');
const token = localStorage.getItem('token');
if(token){
this.props.verifyTokenStart(token);
}else{
this.props.logoutStart();
}
}
render(){
return (
<div className="App">
<Header/>
<Alert/>
<Route exact path="/" component={Home}/>
<Route path="/auth/activate/:token" component={ActivateAccount} />
{!this.props.tokenVerifying && (
<Switch>
<SignedInUserProtectedRoute path="/signup" component={signUp} />
<SignedInUserProtectedRoute path="/signin" component={signIn} />
<AuthRoute path="/user/:id" component={UserComponent}/>
</Switch>
)}
</div>
);
}
}
function mapStateToProps(state){
return {
tokenVerifying : state.user.tokenVerifying
}
}
function mapDispatchToProps(dispatch){
return {
verifyTokenStart : (token) => {dispatch(verifyTokenStart(token))},
logoutStart : () => {dispatch(logoutStart())}
};
}
export default connect(mapStateToProps,mapDispatchToProps)(App);
我在化简器中将变量tokenVerifying设置为true,这基本上意味着在启动应用程序时,它将在本地存储中存在令牌的情况下开始验证令牌,如果没有,则将调用logoutStart方法并将此变量设置为false。在componentDidMount中使用的verifyTokenStart是对服务器的简单api调用,其中包含令牌以检查令牌 我在reducer中将变量tokenVerifying设置为true,这基本上意味着启动应用程序时,它将在本地存储中存在令牌的情况下开始验证令牌,否则将调用logoutStart方法,并且将此变量tokenVerifying设置为false。在componentDidMount中使用的verifyTokenStart是对带有令牌的服务器的简单api调用,用于检查令牌。这是代码,基本上,如果令牌是好的,它将更新状态并将用户加载到reducer中,如我所说,它使用sagas:
function* verifyToken(payload){
const token = payload.payload;
try{
const {data} = yield call(api.verifyToken,{token});
console.log(data);
const {user} = data.data;
yield put(verifyTokenSuccess(user));
}catch(error){
console.log(error.response.data.message);
localStorage.removeItem('token');
yield put(verifyTokenError(error.response.data.message));
}
}
function* onTokenVerify(){
yield takeLatest(UserActionTypes.VERIFY_TOKEN_START,verifyToken);
}
我不会显示化简代码,这是对服务器的标准调用,如果一切正常,将返回用户和令牌。
回到我的问题,我有条件地执行此操作以检查状态是否已加载,因为在通过直接在浏览器中键入url来访问UserComponent时是否不执行该操作,例如:http://localhost:3000/user/dobromir,它会引发异常因为尚未在Redux中加载用户状态。所以我的问题是,这是否是一种不好的做法,是否应该例如在UserComponent中检查this.props.user!==null
并实施任何逻辑,否则我可以保留这样的代码?