簡體   English   中英

ReactJS-store.getState()未定義

[英]ReactJS - store.getState() undefined

我正在使用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()函數中。 我應該在這里設置狀態的正確方法是什么?

使用ES6類時,由於沒有自動綁定,因此需要顯式綁定所有回調。 這可能令人困惑,因為當您使用React.createClassreact將自動將所有回調綁定到組件中,這就是為什么您可以將this.onChange作為回調傳遞的this.onChange

例如。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM