我的 index.js 有以下内容。我已经使用 create-react-app 设置了 React。然后我安装了 redux 并react 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:无法读取未定义的属性“props”
最佳答案
您必须将 doSomething 函数绑定(bind)到组件的上下文,否则 this 将引用渲染的上下文。因此,将代码片段添加到构造函数中
constructor(){
super()
this.doSomething = this.doSomething.bind(this);
}
或 ES6 - 将 doSomething 声明为箭头函数,并且不需要在构造函数中进行绑定(bind)
constructor(){}
doSomething = () => {
....
}
关于reactjs - React Redux 无法从 onClick 中的方法访问 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49166453/