Javascript React render()不';t检测功能的输出变化

Javascript React render()不';t检测功能的输出变化,javascript,reactjs,react-router,Javascript,Reactjs,React Router,因此,我正在使用react router dom创建一个受保护的路由。而且它在某种程度上是有效的 但是,它仅在I从本地存储(从浏览器的GUI)手动删除令牌时起作用 然后我被重定向到/login,成功登录后,我可以访问我的/profile。但是,一旦令牌过期,它将不会从本地存储中删除令牌,也不会从checkAuth()返回false到中的render()中。如何处理这个问题有什么建议吗 import React, { Component } from 'react'; import jwt fro

因此,我正在使用
react router dom
创建一个受保护的路由。而且它在某种程度上是有效的

但是,它仅在I从本地存储(从浏览器的GUI)手动删除令牌时起作用

然后我被重定向到/login,成功登录后,我可以访问我的/profile。但是,一旦令牌过期,它将不会从本地存储中删除令牌,也不会从
checkAuth()
返回false到
中的
render()
中。如何处理这个问题有什么建议吗

import React, { Component } from 'react';
import jwt from 'jsonwebtoken';

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

import Login from './components/Login';
import Profile from './components/Profile';

const checkAuth = () => {
  const token = localStorage.getItem('token');
  const currentTime = Math.floor(new Date().getTime() / 1000);
  const { exp } = jwt.decode(token);

  if (!token) {
    return false;
  }

  if (exp < currentTime) {
    localStorage.removeItem('token');
    return false;
  }
  return true;
};

const AuthRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      checkAuth() ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: '/login',
            state: { from: props.location }
          }}
        />
      )
    }
  />
);

class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <Switch>
          <Route exact path="/login" component={Login} />
          <AuthRoute exact path="/profile" component={Profile} />
        </Switch>
      </BrowserRouter>
    );
  }
}

export default App;
import React,{Component}来自'React';
从“jsonwebtoken”导入jwt;
进口{
浏览器路由器,
路线,,
重新使用
转换
}从“反应路由器dom”;
从“./components/Login”导入登录名;
从“./components/Profile”导入配置文件;
常量checkAuth=()=>{
const token=localStorage.getItem('token');
const currentTime=Math.floor(new Date().getTime()/1000);
const{exp}=jwt.decode(令牌);
如果(!令牌){
返回false;
}
如果(exp<当前时间){
localStorage.removietem('token');
返回false;
}
返回true;
};
常量AuthRoute=({component:component,…rest})=>(
checkAuth()(
) : (
)
}
/>
);
类应用程序扩展组件{
render(){
返回(
);
}
}
导出默认应用程序;

checkAuth()
将调用刷新页面和更改路由。还要确保你的身体状况正常

AuthRoute必须重新渲染才能工作,因此可能您的函数checkAuth工作正常,但由于AuthRoute未从调试中重新渲染而从未被调用,这正是发生的情况。但我不知道如何解决它,因为我是React的初学者。虽然它没有解释为什么
localStorage.removietem()
不会从浏览器中删除令牌。这不会从浏览器中删除令牌,但不会触发重新渲染吗?是的,它不会触发重新渲染,但一旦检测到令牌过期,它也不会删除令牌。它不会删除令牌,因为它没有被调用,因为没有触发重新渲染。