简体   繁体   中英

Action is triggered but store value in not updated

Action triggered but store not updated, when actions are in single object action is not working, separate action with return method its working

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,
            }
        }
    }

What about using this.props instead of store , and make sure you 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);

To use store.dispatch() you have to import store . However I believe this is an anti-pattern, so you will need to use this.props.dispatch() . Moreover this line export default connect(mapStateToProps, {actions})(OrderDashboard); is wrong. You need export default connect(mapStateToProps)(OrderDashboard); and you need to import your actions at the top of the file. So your code should look something like this:

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);

also, not sure why you want to use state and constructor here, but if nothing else is added to your code then remove constructor, super and state

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM