简体   繁体   English

ReactJS-store.getState()未定义

[英]ReactJS - store.getState() undefined

I am getting data from an external api using the altjs implementation of Flux. 我正在使用Flux的altjs实现从外部api获取数据。 The api call works fine from the action, is returned back to the store, and then the onChange() function is triggered in my component. api调用可以从该操作中正常工作,然后返回到商店,然后在我的组件中触发onChange()函数。 I try to set the state from the current state of the store : 我尝试从商店的当前状态设置状态:

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;

I am getting the error "Cannot set property 'state' of undefined" 我收到错误消息“无法设置未定义的属性'状态'”

My store looks like this : 我的商店看起来像这样:

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() doesn't throw any errors in the constructor. this.state = AppStore.getState()在构造函数中不会引发任何错误。 It is just being thrown in the onChange() function. 它只是被扔在onChange()函数中。 What is the proper way I should be setting the state here? 我应该在这里设置状态的正确方法是什么?

When you use ES6 classes you need to bind all the callbacks explicitly since there is no autobind. 使用ES6类时,由于没有自动绑定,因此需要显式绑定所有回调。 It may be confusing since when you use React.createClass , react will automatically bind all the callbacks into the component and thats why you could just pass this.onChange as a callback. 这可能令人困惑,因为当您使用React.createClassreact将自动将所有回调绑定到组件中,这就是为什么您可以将this.onChange作为回调传递的this.onChange

Eg. 例如。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM