【问题标题】:Data Doesn't Update From API in React/Flux App数据不会从 React/Flux 应用程序中的 API 更新
【发布时间】: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


    【解决方案1】:

    您可能想使用setState

    如文档所述:

    永远不要直接改变 this.state,因为之后调用 setState() 可能会替换你所做的改变。将 this.state 视为不可变的。


    另外你的构造函数看起来很奇怪,你真的打算不使用UserActions.getCurrentUser();的结果

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

    【讨论】:

    • 好电话..我同意构造函数。是否可以将UserStore.getCurrentUser() 用于该对象的user 属性?
    • @ironicaldiction 你可以在构造函数中使用this.state = { user:UserStore.getCurrentUser() }。这样,状态在第一个onUserStateChange之前也是有效的。而且你不需要在构造函数中使用 setState。
    猜你喜欢
    • 2016-06-29
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    • 2017-08-14
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多