0
我在项目的前端上使用React + Flux,我需要获取用户名才能在侧边栏上显示它。数据不会从React/Flux应用程序中的API更新
问题:我调用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对象
好call..and我同意的构造。替代方法是使用'UserStore.getCurrentUser()'作为该对象的'user'属性吗? – ironicaldiction
@ironicaldiction你可以在构造函数中使用'this.state = {user:UserStore.getCurrentUser()}'。这样,状态在第一个'onUserStateChange'之前也是有效的。你不需要在构造函数中使用setState。 – Volune