【问题标题】:Using Spread Operator in Redux mapDispatchToProps and SweetAlert2在 Redux mapDispatchToProps 和 SweetAlert2 中使用扩展运算符
【发布时间】:2018-09-30 18:12:43
【问题描述】:

当我在 mapDispatchToProps 中包含 swal 动作创建者时

    function mapDispatchToProps(dispatch) {
        return {
            getAnimal: (_id) => dispatch(getAnimal(_id)),
            ...swal
        }
    }

this.props.getAnimal() 在被调用时可以正确调度动作,但...swal 提供的this.props.showAlert() 在被调用时不会调度动作!

但是,如果我们将 ...swal 扩展运算符替换为:

function mapDispatchToProps(dispatch) {
    return {
        getAnimal: (_id) => dispatch(getAnimal(_id)),
        showAlert: () => dispatch(swal.showAlert()),
        hideAlert: () => dispatch(swal.hideAlert()),
    }
}

我们现在弹出警告对话框(预期行为),但警告框中没有文本出现,并且 JS 控制台显示错误

SweetAlert2:未知参数“show”(sweetalert2.js:122)

问题:mapDispachToProps 中使用...swal 的正确方法是什么,这样您就不必单独选择要将调度映射到的动作创建者?

更完整的代码

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import { swal } from 'react-redux-sweetalert2';
import { getAnimal } from '../../actions';

class Animal extends Component {

    ...    

    function mapStateToProps(state) {
        ...
    }

    function mapDispatchToProps(dispatch) {
        return {
            getAnimal: (_id) => dispatch(getAnimal(_id)),
            ...swal
        }
    }

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Animal))

【问题讨论】:

    标签: javascript reactjs redux sweetalert2


    【解决方案1】:

    简单地说,你不能那样做。您必须使用对象或函数调度操作。更多信息请查看doc

    正确的方法是使用类似的东西:

    function mapDispatchToProps(dispatch) {
            return {
                getAnimal: (_id) => dispatch(getAnimal(_id)),
                swalAlert: (...swal) => dispatch(swalAlert(...swal)
            }
        }
    

    要根据文档返回对象,您可以这样使用:

    const getAnimal = (_id) => dispatch(getAnimal(_id))
    
    export default withRouter(connect(mapStateToProps, { getAnimal, ...swal })(Animal))
    

    【讨论】:

    • 谢谢!您的第二种方法(mapStateToProps, { getAnimal, ...swal })(Animal) 有效!但在你的第一种方法中,我得到swalAlert is not defined。我们如何才能获得第一种工作方法?
    • swalAlert 需要像定义 getAnimal 一样定义。这只是调度程序方法。
    【解决方案2】:

    像这样:

    export default withRouter(connect(mapStateToProps, { ...myActions, ...swal })(Animal))
    

    一定要考虑速记版的优缺点:https://gist.github.com/heygrady/c6c17fc7cbdd978f93a746056f618552#object-short-hand-version

    【讨论】:

      猜你喜欢
      • 2020-04-06
      • 1970-01-01
      • 2019-03-13
      • 2020-05-09
      • 2017-03-16
      • 2018-02-19
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      相关资源
      最近更新 更多