【发布时间】:2018-03-17 19:26:24
【问题描述】:
所以我在更新组件的状态时遇到了问题。 this.state.authenticated 被传递给 Navigation 以隐藏/显示登录/注销按钮。但是,一旦用户登录,状态更改就不会重新呈现导航。我必须手动刷新页面才能看到导航栏重新呈现并显示注销按钮。
这里是代码
const token = window.localStorage.getItem("token");
class App extends Component {
constructor(props) {
super(props);
this.state = {
authenticated: false,
}
}
componentWillMount() {
console.log('app token:', token);
if (token) {
this.setState({ authenticated: true});
} else {
this.setState({authenticated: false});
}
console.log('app componet will mount:', this.state.authenticated);
}
render() {
return (
<div className="App">
<Navigation authenticated={this.state.authenticated}/>
<Route path='/' exact component={Register} />
<Route path='/feed' exact component={Feed} />
<Route path='/login' component={Login} />
<Route path='/feed/:id' component={SingleGroup} />
<Route path='/mygroups' component={MyGroups} />
</div>
);
}
}
登录操作代码
export const login = (username, password, history) => {
axios.defaults.withCredentials = true;
return (dispatch) => {
axios.post(`${url}/user/login`, {username, password})
.then((data) => {
dispatch({
type: 'SIGNIN_USER',
payload: data,
})
window.localStorage.setItem('token', data.data.token);
history.push('/feed');
})
.catch((err) => {
dispatch({
type: 'SIGNIN_ERROR',
payload: err,
});
});
};
};
【问题讨论】:
-
令牌从何而来?
-
我从本地存储中获取它。如果用户认证成功则设置
-
它的代码在哪里?
-
添加到问题
-
好的,很好。现在你从哪里得到令牌?获取token的代码在哪里?
标签: reactjs