Reactjs React redux调度不可用
最初,我在Reactjs React redux调度不可用,reactjs,ecmascript-6,redux,redux-thunk,Reactjs,Ecmascript 6,Redux,Redux Thunk,最初,我在index.js上调用了这个函数来触发主数据的加载: const store = configureStore(); store.dispatch(doStuff()); 现在我想做下一步,在页面级别加载这些数据(看起来更好) 我以盖隆的这篇文章为基础: 我有以下代码: import React, { Component } from 'react'; import { connect } from 'react-redux'; import { PropTypes } fro
index.js
上调用了这个函数来触发主数据的加载:
const store = configureStore();
store.dispatch(doStuff());
现在我想做下一步,在页面级别加载这些数据(看起来更好)
我以盖隆的这篇文章为基础:
我有以下代码:
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);
我所看到的(最重要的)区别是我进行了映射:
export default connect(mapStateToProps, mapDispatchToProps)(MyPage);
我需要做些什么才能让它工作
可能是简单的事情,但我看不出来。解释一下:
如果不提供自己的mapDispatchToProps函数或对象
默认的mapDispatchToProps实现中充满了动作创建者
只需将dispatch注入组件的道具中
当您没有将mapDispatchToProps
参数传递到connect
时,react-redux会将dispatch
作为道具传递给包装组件
如果将mapDispatchToProps
传递到connect
,则传递包装动作,而不是dispatch
,并且此.props.dispatch
未定义
因此,如果您需要在组件中使用
dispatch
,请不要使用mapDispatchToProps
,或者将所有操作都用dispatch
封装在mapDispatchToProps
中。。。我根本不需要盖隆的剧本。我所要做的就是从构造函数调用操作列表:
class MyPage extends Component {
constructor(props, context) {
super(props, context);
props.actions.doStuff();
this.state = {
myStuff: []
}
}
render() {
return (
<MuiThemeProvider>
<div>...</div>
</MuiThemeProvider>
);
}
}
这是可用的,因为它映射在mapDispatchToProps
:
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(loadOrderActions, dispatch)
};
}
我确实需要
mapDispatchToProps
方法,因为这就是我更新状态的方式。那么,解决方案是什么呢?解决方案是在mapDispatchToProps
中用dispatch
包装您的操作。我希望这可以帮助您为什么不在mapDispatchToProps
中执行所有dispatch()
调用?您真的需要在组件内部调用dispatch吗(这与同一文件中的不同)?
props.actions.doStuff();
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(loadOrderActions, dispatch)
};
}