【问题标题】:How to dispatch more than one action in mapDispatchToProps in react-redux如何在 react-redux 的 mapDispatchToProps 中调度多个动作
【发布时间】:2017-04-17 20:02:50
【问题描述】:

mapDispatchToProps 中有三个函数。我想在 React Component 的构造函数中使用它们的任何函数,但是当我使用 console.log(this.props)it 时,它给出了未定义的如何在构造函数中使用这些函数从 firebase 数据库加载数据?

mapDispatchToProps

const mapDispatchToProps = (dispatch) => {
    return {
        addProductRequest: (data) => {
            console.log(data)
            dispatch(AddNewProduct(data))
        },
        loadProducts: () => {
            dispatch(ViewProducts())
        },
        loadStores: () => {
            dispatch(ViewStores())
        },
    }
}

构造函数

constructor() {
    super();
    this.state = {
        products: [],
        stores: [],
        currentProduct: [],
        stockAvailable: [],
        productName: '',
        description: '',
        qty: 0,
        unitPrice: 0,
        storeName: '',
        selectedProduct: '',
        productNameInStock: '',
        productQtyInStock:0
    }
    console.log(this.props)

    this.props.loadProducts();
    this.props.loadStores();

    this.submit = this.submit.bind(this);
    this.inputHandler = this.inputHandler.bind(this);
}

报错

未捕获的类型错误:无法读取未定义的属性“loadProducts”

【问题讨论】:

  • 而不是使用mapDispatchToProps,为什么不这样做this.props.dispatch(ViewProducts())。在我看来要清楚得多。
  • 我可以用但是我想用在mapDispatchToProps中,谢谢你的建议

标签: reactjs redux react-redux


【解决方案1】:

您将使用来自reduxbindActionCreators,f.e.:

const mapDispatchToProps = (dispatch) => {
    return {
        ...bindActionCreators({ loadProducts, loadStores }, dispatch)
    }
}

在这种情况下,您将能够通过组件中的this.props.loadProducts() 创建操作。

【讨论】:

    【解决方案2】:

    现在它工作了,我忘了在构造函数中传递道具

    constructor(props) {
        super();
        this.state = {
            products: [],
            stores: [],
            currentProduct: [],
            stockAvailable: [],
            productName: '',
            description: '',
            qty: 0,
            unitPrice: 0,
            storeName: '',
            selectedProduct: '',
            productNameInStock: '',
            productQtyInStock:0
        }
        console.log(props)
    
        props.loadProducts();
        props.loadStores();
    
        this.submit = this.submit.bind(this);
        this.inputHandler = this.inputHandler.bind(this);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-15
      • 2021-10-14
      • 2021-10-06
      • 1970-01-01
      • 2018-11-10
      • 1970-01-01
      • 2019-05-27
      • 1970-01-01
      相关资源
      最近更新 更多