Javascript 我可以在React(tsx)应用程序中将解码JWT中的信息设置为状态吗?
我一直在用Legacy React构建一个应用程序,使用TypeScript(不是很有趣,而是很好的实践)。我的一个组件从本地存储中提取jwt(我知道这不是它应该在的位置,但现在…),并将其设置为状态属性simpleToken。有效载荷有一条信息,我很想在我的应用程序的其他部分中使用。我已经解码了令牌,能够Javascript 我可以在React(tsx)应用程序中将解码JWT中的信息设置为状态吗?,javascript,reactjs,typescript,jwt,state,Javascript,Reactjs,Typescript,Jwt,State,我一直在用Legacy React构建一个应用程序,使用TypeScript(不是很有趣,而是很好的实践)。我的一个组件从本地存储中提取jwt(我知道这不是它应该在的位置,但现在…),并将其设置为状态属性simpleToken。有效载荷有一条信息,我很想在我的应用程序的其他部分中使用。我已经解码了令牌,能够console.log(JSON.parse(atob(token.split('.')[1]))有效负载的信息,但是我还没有找到一种方法来提取信息并将其设置为状态 import React
console.log(JSON.parse(atob(token.split('.')[1]))
有效负载的信息,但是我还没有找到一种方法来提取信息并将其设置为状态
import React from 'react';
import { Route, Switch, BrowserRouter as Router } from "react-router-dom";
import "../../App.css";
import { Row, Col } from "reactstrap";
import Main from './main'
import CharacterIndex from '../app/characters/CharacterIndex';
import Auth from '../auth/Auth';
import UserIndex from '../app/user/UserIndex';
import JWT from '../app/types/Jwt';
type SidebarState = {
simpleToken: string,
userId: JWT,
}
type SidebarProps = {
token: string | null,
clickLogout: () => void,
loginStatus: Function
}
class Sidebar extends React.Component <SidebarProps, SidebarState> {
constructor(props: SidebarProps){
super(props)
this.state= {
simpleToken: '',
userId: {id:0, iat:0, exp: 0},
}
}
tokenValidation() {
if(this.props.token !== null){
this.setState({
simpleToken: this.props.token
})
}
}
//Below we are coding our custom function for decoding our jwt
tokenDecoder(token: string) {
this.setState({ userId: JSON.parse(atob(token.split('.')[1]))
})
console.log("decoder Hit", this.state.userId)
}
componentWillMount() {
this.tokenValidation()
}
//Testing our decoding of the token. This will give us user data to play with
componentDidMount() {
this.tokenDecoder(this.state.simpleToken);
}
期待有任何想法!从userToken派生userId不是一个好的做法。您应该使用该令牌在此处调用用户配置文件信息。
export default interface JWT {
id: number,
iat: number,
exp: number
}