触发了动作但未更新存储,当动作在单个对象中时动作不起作用,使用返回方法起作用的单独动作
actions.js
export const actions = {
GET_ORDERS_COUNT:'GET_ORDERS_COUNT'
};
order.js
class OrderDashboard extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
componentDidMount() {
store.dispatch({
type: actions.GET_ORDERS_COUNT
});
}
}
export default connect(mapStateToProps, {actions})(OrderDashboard);
reducer.js
const initState = {
dashboardData:0
};
export default function (state = initState, action) {
switch (action.type) {
case actions.GET_ORDERS_COUNT: {
return {
...state,
dashboardData: 5,
}
}
}
答案 0 :(得分:0)
使用this.props
代替store
,并确保您import { connect } from react-redux
import { connect } from 'react-redux'
class OrderDashboard extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
componentDidMount() {
this.props.dispatch({
type: actions.GET_ORDERS_COUNT
});
}
}
export default connect(mapStateToProps, {actions})(OrderDashboard);
答案 1 :(得分:0)
要使用store.dispatch()
,您必须导入store
。但是,我认为这是一种反模式,因此您将需要使用this.props.dispatch()
。此外,此行export default connect(mapStateToProps, {actions})(OrderDashboard);
是错误的。您需要export default connect(mapStateToProps)(OrderDashboard);
,并且需要在文件顶部导入actions
。因此,您的代码应如下所示:
import {actions} from './actions';
class OrderDashboard extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
componentDidMount() {
this.props.dispatch({type:actions.GET_ORDERS_COUNT})
}
}
export default connect(mapStateToProps)(OrderDashboard);
也不确定在这里为什么要使用状态和构造函数,但是如果没有其他内容添加到代码中,则删除构造函数,super和state