Mor*_*hal 5 reactjs react-router react-redux
我对React和尝试学习它很陌生,但是在后端有很强的背景(java / nodejs / php / ...)
所以首先我想创建一个登录门户,基本上是3个页面:-如果您未通过身份验证,则该页面会将您重定向到登录页面-登录页面-注册页面
功能正在运行(注册/登录/注销)我的问题在主页上,如果我首先使用user1登录,我会看到Hello user1。如果我注销并使用user2登录,我仍然会看到user1。
看来变量是由浏览器某种方式缓存的。F5刷新实际上会更新值...:/
这是我所做的:
在我的应用中,我有以下路线:
<Provider store={store}>
<HashRouter>
<Switch>
<Route path="/login" name="Login" component={Login} />
<Route path="/register" name="Register" component={Register} />
<PrivateRoute path="/" name="Home" component={Layout} />
</Switch>
</HashRouter>
</Provider>
Run Code Online (Sandbox Code Playgroud)
提供程序configureStore正在执行以下操作:
store.dispatch(requestUserInfo());
Run Code Online (Sandbox Code Playgroud)
这个requestUserInfo()是我在以下类中创建的东西:获取令牌,使用jwt对其进行解码,并呈现一些用户信息:
import jwt_decode from 'jwt-decode'
export const REQUEST_USER = "REQUEST_USER";
export const USER_INFO = "USER_INFO";
export function requestUserInfo() {
if(localStorage.usertoken){
const decoded = jwt_decode(localStorage.usertoken)
let usertest = {
"username": decoded.first_name + " " + decoded.last_name,
"picture": "assets/img/avatars/test.png",
"activity": 1
}
return dispatch => {
dispatch({
type: USER_INFO,
payload: usertest
});
};
} else {
return dispatch => {
dispatch({
type: USER_INFO,
payload: {"username": "","picture": "","activity": 0}
});
};
}
}
export default function isLogged() {
let status = false
if(localStorage.usertoken){
try{
if(jwt_decode(localStorage.usertoken)){
status = true;
}
} catch(e){
console.log(e)
}
}
return status
}
Run Code Online (Sandbox Code Playgroud)
注销时,我通过执行以下操作删除了令牌:localStorage.removeItem('usertoken')
编辑:尝试在私有选项卡中进行第一次登录时,什么都没有显示,变量为空。看起来我的变量是在渲染后设置的吗?
Edit2:我把所有东西都放在了github上,所以它可能更容易调试:https : //github.com/senechalm/learning-reactjs
是否有人对如何解决此问题/错误有任何想法/建议?
我可以在存储库中看到一些我们可以通过 3 个步骤修复的问题:
requestUserInfo()以便我们返回操作,但不调用调度:export function requestUserInfo() {
if(sessionStorage.usertoken){
const decoded = jwt_decode(localStorage.usertoken)
let usertest = {
"username": decoded.first_name + " " + decoded.last_name,
"picture": "assets/img/avatars/sunny.png",
"activity": 12
}
return {
type: USER_INFO,
payload: usertest
};
} else {
return {
type: USER_INFO,
payload: {username: "",picture: "",activity: 0}
};
}
}
Run Code Online (Sandbox Code Playgroud)
const mapStateToProps = (state) => state.user;
function mapDispatchToProps (dispatch) {
return {
requestUserInfo: ()=> dispatch(requestUserInfo())
}
}
export default connect(mapStateToProps,mapDispatchToProps)(Home);
Run Code Online (Sandbox Code Playgroud)
componentDidMount为 UNSAFE 的 now componentWillMount,因此将其删除并添加:componentDidMount() {
console.log("before"+this.props.username)
this.props.requestUserInfo();
console.log("after"+this.props.username)
}
Run Code Online (Sandbox Code Playgroud)
希望这是有道理的:)
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |