Reactjs,这.上下文在构造函数方法中未定义

Reactjs, this.context is undfined in constructor method

本文关键字:方法 未定义 构造函数 上下文 Reactjs      更新时间:2023-09-26

我实际上正在尝试开发一个简单的组件,对应于一个列表,当我按下一个按钮时,我将再填充一个项目。

我的问题是我使用ES6,所以我不使用getInitialState,我使用构造函数进行初始化,就像在文档中解释的那样。

我的问题是,现在,这。context在构造函数中是未定义的,我不能直接在构造函数中获得我的第一次数组(或预加载的数组):

import React from 'react';
import ListStore from '../stores/ListStore';
class Client extends React.Component {

  constructor(props){
    super(props);
    this.state = this.getStoreState(); // throw me that in getStoreState, this.context is undefined
  }

  static contextTypes = {
      executeAction: React.PropTypes.func.isRequired,
      getStore: React.PropTypes.func.isRequired
  };
  componentDidMount() {
      this.context.getStore(ListStore).addChangeListener(this._onStoreChange.bind(this));
  }
  componentWillUnmount() {
      this.context.getStore(ListStore).removeChangeListener(this._onStoreChange.bind(this));
  }
  _onStoreChange () {
     this.setState(this.getStoreState());
 }
  getStoreState() {
      return {
          myListView: this.context.getStore(ListStore).getItems() // gives undefined
      }
  }

  add(e){
    this.context.executeAction(function (actionContext, payload, done) {
        actionContext.dispatch('ADD_ITEM', {name:'toto', time:new Date().getTime()});
    });
  }
  render() {
      return (
          <div>
              <h2>Client</h2>
              <p>List of all the clients</p>
              <button onClick={this.add.bind(this)}>Click Me</button>
              <ul>
                  {this.state.myListView.map(function(test) {
                    return <li key={test.time}>{test.name}</li>;
                  })}
              </ul>
          </div>
      );
  }
}

export default Client;

我只是想在构造函数中预加载数组,即使它是空的或不空的,这正是我的store返回的:

从' flexible/addons/BaseStore'导入BaseStore;

class ListStore extends BaseStore {
  constructor(dispatcher) {
      super(dispatcher);
      this.listOfClient = [];
    }
  dehydrate() {
      return {
          listOfClient: this.listOfClient
      };
  }
  rehydrate(state) {
      this.listOfClient = state.listOfClient;
  }

  addItem(item){
    this.listOfClient.push(item);
    this.emitChange();
  }
  getItems(){
    return this.listOfClient;
  }
}
ListStore.storeName = 'ListStore';
ListStore.handlers = {
    'ADD_ITEM': 'addItem'
};
export default ListStore;

谢谢你的帮助

你面临的问题是因为你的组件应该是无状态的,我再怎么说也不为过,state应该存在于你的商店里,(I-state,"可以")。生活在你的组件中,但这是有争议的)

你应该做的是使用一个更高级的组件,把你的react组件封装在一个更高级的组件中,让那个组件从store中获取状态,并把它作为props传递给你的组件。

这样你就不需要初始化状态,你只需要设置你的defaultProps和propTypes。

这样你的组件是无状态的,你可以完全利用react的生命周期,它也变得可重用,因为你不需要在你的组件中获取实际数据的逻辑。

好读

  • props vs state: https://github.com/uberVU/react-guide/blob/master/props-vs-state.md)

  • 高级组件:http://browniefed.com/blog/2015/05/02/react/

希望这对你有帮助