React Redux 无法从 onClick 中的方法访问道具

React Redux cannot access props from method in onClick

我的 index.js 有以下内容。我已经使用 create-react-app 设置了 React。然后我安装了 redux 并反应了 redux。

import React from 'react';
import ReactDOM from 'react-dom';
import AppContainer from './AppContainer';
import {createStore} from 'redux'
import {Provider} from 'react-redux'

const defaultState = {
    activeTab: 'firstTab'
};

const reducer = function(state=defaultState, action){
    switch (action.type) {
        case 'TAB_CHANGED':
            return state.merge({
                activeTab: state.activeTab
            })
        default: return state;
    }
};
const store = createStore(reducer);

ReactDOM.render(
    <Provider store={store}>
        <AppContainer />
    </Provider>,
    document.getElementById('root')
);

以及我的 AppContainer.js

以下内容
import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux'

class AppContainer extends React.Component {
  static propTypes = {
      activeTab: PropTypes.string.isRequired,
      dispatch: PropTypes.func.isRequired,
  }

  doSomething = function(){
      this.props.dispatch('TAB_CHANGED', {activeTab: Math.random().toString(36).substring(7)})
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">{ this.props.activeTab }</h1>
        </header>
        <p className="App-intro">
            <button onClick={this.doSomething}>Do Something</button>
        </p>
      </div>
    );
  }
}

function mapStateToProps(state){
    return state;
}

export default connect(mapStateToProps)(AppContainer);

页面在首次呈现时加载正常。 react dom 可以访问 this.props.activeTab。但是,当我单击 Do Something 按钮时,出现以下错误:TypeError: Cannot read property 'props' of undefined

您必须将 doSomething 函数绑定到组件的上下文,否则它将引用渲染的上下文。所以将代码片段添加到构造函数

constructor(){
    super()
    this.doSomething = this.doSomething.bind(this);
}

ES6 - 将 doSomething 声明为箭头函数,构造函数中不需要绑定

constructor(){}
doSomething = () => {
....
}