最初,我在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不是函数
let doStuff = function() {
dispatch(myActions.doStuff())
};
我看到的(最重要的)差异是我做映射:
export default connect(mapStateToProps, mapDispatchToProps)(MyPage);
我需要做些什么才能让它发挥作用?
可能很容易,但我看不到它。
答案 0 :(得分:1)
Connect's react-redux docs解释说:
如果您不提供自己的mapDispatchToProps函数或对象 完整的动作创建者,默认的mapDispatchToProps实现 只需将调度注入组件的道具。
如果您未将mapDispatchToProps
参数传递给connect
,则react-redux会将dispatch
作为道具传递给包裹的组件。
如果您将mapDispatchToProps
传递给connect
,则会传递包装的操作而不是dispatch
,并且this.props.dispatch
未定义。
因此,如果您的组件中需要dispatch
,请不要使用mapDispatchToProps
,或将dispatch
内的所有操作包裹在mapDispatchToProps
内。
答案 1 :(得分:0)
哦,小男孩......我根本不需要Gaearon的剧本。我所要做的就是从构造函数中调用动作列表:
class MyPage extends Component {
constructor(props, context) {
super(props, context);
props.actions.doStuff();
this.state = {
myStuff: []
}
}
render() {
return (
<MuiThemeProvider>
<div>...</div>
</MuiThemeProvider>
);
}
}
这是重要的一行:
props.actions.doStuff();
哪个可用,因为它已映射到mapDispatchToProps
:
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(loadOrderActions, dispatch)
};
}