如何基于Web令牌修复三元如果REACT重定向声明

问题描述 投票:0回答:1

我想检查是否有在localStorage的,如果是一个令牌,转到coorisponding组件,如果没有,我想页转到登录页面。

如果我手动更改“authTokenhas ===真”到“authTokenhas!== true”,可以正常工作所以才出现,我不能正确构建if语句?

import React from 'react';
import {
  Redirect,
  Route
} from 'react-router-dom';

var authTokenhas = localStorage.getItem('token');


const PrivateRoute = ({component: Component, ...rest}) => (

  <Route {...rest} render={(props) => (
    authTokenhas === true
    ? <Component {...props}/>
    : <Redirect to={{
      pathname: '/login',
      state: { from: props.location }
    }}/>
  )}/>
)

export default PrivateRoute;
reactjs react-router
1个回答
3
投票

问题的存在,因为你是比较authTokenhas使用真实strict equality (===)'true'永远不会严格相等true

the docslocalStorage.getItem将始终返回DOMString,这将永远不会严格等于true。您应该令牌转换为布尔,或关闭严格的检查,并使用0或1(使​​用字符串如真或假都会让你陷入困境。(见console.log(!!'false'))。

© www.soinside.com 2019 - 2024. All rights reserved.