【发布时间】:2018-06-28 20:13:59
【问题描述】:
最初我在index.js 打了这个电话来触发我的主要数据的加载:
const store = configureStore();
store.dispatch(doStuff());
现在我想做下一步并在页面级别加载这些数据(似乎更好)。
我以 Gaearon 在Redux github 的这篇帖子为基础:
我有这个代码:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { PropTypes } from 'prop-types';
import { bindActionCreators } from 'redux';
import * as myActions from '../../actions/myActions';
import { MuiThemeProvider } from 'material-ui/styles';
let createHandlers = function(dispatch) {
let doStuff = function() {
dispatch(myActions.doStuff())
};
return {
doStuff,
// other handlers
};
}
class MyPage extends Component {
constructor(props, context) {
super(props, context);
this.handlers = createHandlers(this.props.dispatch);
//this.handlers.doStuff();
this.state = {
myStuff: []
}
}
render() {
return (
<MuiThemeProvider>
<div>...</div>
</MuiThemeProvider>
);
}
}
function mapStateToProps(state, ownProps) {
return {
// Set state
};
}
function mapDispatchToProps(dispatch) {
return {
// Set state
};
}
MyPage.propTypes = {
// My props
}
export default connect(mapStateToProps, mapDispatchToProps)(MyPage);
问题
当我取消注释该行时,我收到此错误:
TypeError: dispatch is not a function
let doStuff = function() {
dispatch(myActions.doStuff())
};
我看到的(最重要的)区别是我做映射:
export default connect(mapStateToProps, mapDispatchToProps)(MyPage);
我需要做什么才能让它工作?
可能很简单,但我没看到。
【问题讨论】:
-
为什么不在
mapDispatchToProps内完成所有dispatch()调用?你真的需要在你的组件内部调用 dispatch(这与在同一个文件中不同)吗?
标签: reactjs ecmascript-6 redux redux-thunk