2017-04-17 24 views
2

mapDispatchToProps中有三個函數。我想在React Component的構造函數中使用它們中的任何函數,但是當我使用console.log(this.props)時,它給出了未定義的如何在構造函數中使用這些函數從Firebase數據庫加載數據?如何在react-redux中的mapDispatchToProps中分派多個動作

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

它給出了一個錯誤

Uncaught TypeError: Cannot read property 'loadProducts' of undefined

+1

,而不是使用'mapDispatchToProps'爲什麼不只是做這樣的'this.props.dispatch(ViewProducts())'。在我看來更清楚。 – Abhishek

+1

我可以使用它,但我想在mapDispatchToProps中使用,感謝您的建議 –

回答

4

你會使用bindActionCreatorsredux,f.e:

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

在這種情況下,您將能夠通過組件中的this.props.loadProducts()創建操作。現在

0

它的工作,我忘了通過道具構造

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); 
} 
相關問題