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