2016-03-04 25 views
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對象

回答

1

你可能想使用setState

由於文檔說:

不要直接改變this.state,因爲之後調用setState()可能會替換你的m ADE。將this.state視爲不可變的。


而且你的構造似乎很奇怪,你真的打算不使用UserActions.getCurrentUser();結果在

UserActions.getCurrentUser(); 
this.state = { 
    user: {} 
}; 
+0

好call..and我同意的構造。替代方法是使用'UserStore.getCurrentUser()'作爲該對象的'user'屬性嗎? – ironicaldiction

+0

@ironicaldiction你可以在構造函數中使用'this.state = {user:UserStore.getCurrentUser()}'。這樣,狀態在第一個'onUserStateChange'之前也是有效的。你不需要在構造函數中使用setState。 – Volune

相關問題