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

时间:2018-03-08 06:04:23

标签: reactjs react-redux react-proptypes

我的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);

首次渲染时页面加载正常。反应dom可以访问this.props.activeTab。但是当我点击Do Something按钮时,我收到以下错误:TypeError: Cannot read property 'props' of undefined

1 个答案:

答案 0 :(得分:3)

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

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

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

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