mapDispatchToProps中有三个函数。我想在React Component的构造函数中使用它们中的任何函数,但是当我使用console.log(this.props)
时,它给出了未定义的如何在构造函数中使用这些函数从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);
}
它出错了
未捕获的TypeError:无法读取属性' loadProducts'未定义的
答案 0 :(得分:7)
您可以使用bindActionCreators
中的redux
,例如:
const mapDispatchToProps = (dispatch) => {
return {
...bindActionCreators({ loadProducts, loadStores }, dispatch)
}
}
在这种情况下,您将能够通过组件中的this.props.loadProducts()
创建操作。
答案 1 :(得分: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);
}