2016-03-04 64 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

相关问题