【问题标题】:ReactJS - store.getState() undefinedReactJS - store.getState() 未定义
【发布时间】:2016-05-22 08:37:27
【问题描述】:

我正在使用 Flux 的 altjs 实现从外部 api 获取数据。 api 调用从操作中正常工作,返回到商店,然后在我的组件中触发 onChange() 函数。我尝试从商店的当前状态设置状态:

import React, { Component, PropTypes } from 'react';
import AppStore from '../../stores/AppStore';
import AppActions from '../../actions/AppActions';

const title = 'Contact Us';


class ContactPage extends Component {

    constructor(props) {
        super(props);
        this.state = AppStore.getState();
    }

  static contextTypes = {
    onSetTitle: PropTypes.func.isRequired,
  };

  componentWillMount() {
    AppActions.getData();
    this.context.onSetTitle(title);
    AppStore.listen(this.onChange)
}

componentWillUnmount() {
    AppStore.unlisten(this.onChange)
}

onChange() {
    this.state = AppStore.getState();
}

  render() {
    return (
      <div className={s.root}>
        <div className={s.container}>
          <h1>{title}</h1>
          <span>{this.state.data.id}</span>
        </div>
      </div>
    );
}

}

export default ContactPage;

我收到错误“无法设置未定义的属性‘状态’”

我的店铺是这样的:

import alt from '../alt';
import AppActions from '../actions/AppActions';

class AppStore {
    constructor() {
        this.bindActions(AppActions);
        this.loading = false;
        this.data = {};
        this.error = null
    }

    onGetDataSuccess(data) {
        this.data = data;
    }
}

export default alt.createStore(AppStore, 'AppStore');

this.state = AppStore.getState() 不会在构造函数中抛出任何错误。它只是在 onChange() 函数中抛出。我应该在这里设置状态的正确方法是什么?

【问题讨论】:

    标签: javascript reactjs reactjs-flux alt.js


    【解决方案1】:

    当您使用 ES6 类时,您需要显式绑定所有回调,因为没有自动绑定。这可能会让人感到困惑,因为当您使用 React.createClassreact will automatically bind 时,所有的回调都进入了组件,这就是为什么您可以将 this.onChange 作为回调传递。

    例如。

    componentWillMount() {
      ...
      AppStore.listen(this.onChange.bind(this));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      • 2016-09-01
      • 2015-09-21
      • 1970-01-01
      相关资源
      最近更新 更多