【发布时间】:2016-03-04 01:18:56
【问题描述】:
我在一个项目的前端使用 React + Flux,我需要获取用户名才能将其显示在侧边栏上。
问题:我在 es6 类的 constructor 中调用该操作,该操作从 API 获取所需的数据,我可以看到它从 onUserStateChanged 方法记录到控制台,但它没有得到更新在渲染方法中的状态。我不明白如何才能在组件中反映状态变化。
export default class extends React.Component {
constructor() {
super();
UserActions.getCurrentUser();
this.state = {
user: {}
};
}
componentDidMount() {
UserStore.addChangeListener(this.onUserStateChange);
}
componentWillUnmount() {
UserStore.removeChangeListener(this.onUserStateChange);
}
onUserStateChange() {
console.log('called');
this.state = {
user: UserStore.getCurrentUser()
};
console.log(this.state);
}
render(){
var _this = this;
return (
console.log(this.state);
<div>{_this.state.user.username}</div>
);
}
}
从onUserStateChange() 对console.log 的调用包含从 API 返回的正确状态,而渲染中的 console.log 仅显示一个空白 JS 对象
【问题讨论】:
标签: javascript reactjs flux