MapDispatchToProps doesn't work on returning a

2019-07-31 09:11发布

问题:

If I make my own mapDispatchToProps function, it doesn't work. If I give a plain object for connect then it does work, but I need the dispatch functionality.. for eg loading of translations per page, Am I doing something wrong here?

const mapStateToProps = (state) => { 

    const { isFetching, lastUpdated, items, errors } = state.transactions; // fetch from redux state ;)

    return {
        translate: getTranslate(state.locale),
        isFetching,
        lastUpdated,
        items,
        errors
    }
} 
const mapDispatchToProps = dispatch => {

    return { 
        fetchTransactionsIfNeeded, 
        invalidateList 
     }
}
export default connect(mapStateToProps, mapDispatchToProps)(Transactions);

The code below works

const mapStateToProps = (state) => { 

    const { isFetching, lastUpdated, items, errors } = state.transactions; // fetch from redux state ;)

    return {
        translate: getTranslate(state.locale),
        isFetching,
        lastUpdated,
        items,
        errors
    }
} 

export default connect(mapStateToProps, { 
       fetchTransactionsIfNeeded, 
       invalidateList 
})(Transactions);

回答1:

According to the redux documentation

[mapDispatchToProps(dispatch, [ownProps]): dispatchProps] (Object or Function): If an object is passed, each function inside it is assumed to be a Redux action creator. An object with the same function names, but with every action creator wrapped into a dispatch call so they may be invoked directly, will be merged into the component’s props.

If a function is passed, it will be given dispatch as the first parameter. It’s up to you to return an object that somehow uses dispatch to bind action creators in your own way. (Tip: you may use the bindActionCreators() helper from Redux.)

In first case when you implement mapDispatchToProps, you are returning a plain object, but you need to use dispatch in it, since its not assumed as an action creator by itself by redux.

You would implement it like

const mapDispatchToProps = dispatch => {

    return { 
        fetchTransactionsIfNeeded: (...args) => {
               dispatch(fetchTransactionsIfNeeded(...args))
         }, 
        invalidateList: (...args) => {
               dispatch(invalidateList(...args))
         },
     }
}

or else don't create it as a function but simply an object

const mapDispatchToProps = { 
       fetchTransactionsIfNeeded, 
       invalidateList 
}