MapDispatchToProps不能用于返回对象

问题描述 投票:1回答:1

如果我创建自己的mapDispatchToProps函数,它就不起作用。如果我给一个普通的对象进行连接,那么它确实有效,但我需要调度功能..例如,每页加载翻译,我在这里做错了吗?

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

以下代码有效

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);
reactjs react-redux
1个回答
1
投票

根据redux文档

[mapDispatchToProps(dispatch,[ownProps]):dispatchProps](Object或Function):如果传递了一个对象,则假定其中的每个函数都是一个Redux动作创建者。具有相同功能名称的对象,但每个动作创建者都包含在一个调度调用中,因此可以直接调用它们,它们将合并到组件的props中。

如果传递了一个函数,它将被赋予dispatch作为第一个参数。由您来返回一个以某种方式使用dispatch以您自己的方式绑定动作创建者的对象。 (提示:您可以使用Redux中的bindActionCreators()帮助程序。)

在第一种情况下,当您实现mapDispatchToProps时,您将返回一个普通对象,但您需要在其中使用dispatch,因为它不会被redux假定为动作创建者。

你会像它一样实现它

const mapDispatchToProps = dispatch => {

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

或者不要将其创建为函数,而只是创建一个对象

const mapDispatchToProps = { 
       fetchTransactionsIfNeeded, 
       invalidateList 
}
© www.soinside.com 2019 - 2024. All rights reserved.