我使用react-redux将React与Redux存储连接起来,并使用“connect”API将“dispatch”属性注入组件。但该组件未收到“dispatch”属性。以下是演示我遇到的问题的代码:
"use strict"
var React = require('react');
var ReactDOM = require('react-dom');
var Redux = require('redux');
var ReactRedux = require('react-redux');
var Provider = ReactRedux.Provider;
function menuManager(state = {count: 0}, action) {
switch (action.type) {
case 'ADD':
return state + 1;
case 'REMOVE':
return state - 1;
default:
return state;
}
}
let store = Redux.createStore(menuManager);
let TestLab = React.createClass({
onRemove: function(itemRemove) {
// this.props.dispatch undefined.
this.props.dispatch({type: 'REMOVE'});
},
onAdd: function() {
const { dispatch } = this.props
// this.props.dispatch undefined.
this.props.dispatch({type: 'ADD'});
},
getInitialState: function() {
return { count: 0 };
},
render: function() {
return (
<div>
<p>Total count: { this.state.count }</p>
<button type="button" onClick={this.onAdd}>Add Item</button>
</div>
);
}
});
function select(state) {
return state;
}
ReactRedux.connect(select)(TestLab);
var target = document.createElement('div');
document.body.appendChild(target);
ReactDOM.render(<Provider store={store}><TestLab /></Provider>, target);
当我尝试调用“this.props.dispatch”时,出现“this.props.dispatch”未定义的错误。
答案 0 :(得分:6)
您没有使用关联的组件connect()
returns a new component。
TestLab = ReactRedux.connect(select)(TestLab);
ReactDOM.render(<Provider store={store}><TestLab /></Provider>, target);
你也会遇到其他一些问题,即你正在使用this.state.count
而不是this.props.count
,你的reducer函数会尝试增加或减少一个对象而不是整数。< / p>