在我的 react redux 项目中,我试图将道具从子组件传递到父组件。更具体地说,我想将两条信息传递给父容器:产品和计数器,这两条信息都打算在函数内部使用,如下所示:
addProductToBasket(product, counter) {
}
我的问题是:在 addProductToBasket 函数中无法识别计数器,我收到以下错误消息:
未捕获的 ReferenceError:未定义计数器
为什么这里没有定义计数器,我怎样才能在这个函数中正确使用它?
这是相关的父容器代码:
class Products extends React.Component {
constructor(props) {
super(props);
this.state = {
listOn: false,
total: 0,
}
this.addProductToBasket = this.addProductToBasket.bind(this);
}
addProductToBasket(product, counter) {
var price = Number(product.price);
console.log(price);
this.setState(prevState => ({
total: prevState.total + price,
}),
() => {
var total = this.state.total
console.log(counter);
this.props.updateBasket(total, price, counter, product);
})
}
render() {
const grid = this.props.products.map((product, i) => {
return (
<GridLayout
key={i}
name={product.name}
id={product.id}
description={product.description}
price={product.price}
addProductToBasket={() => this.addProductToBasket(product, counter)}
/>
);
});
return(
<Grid>
<Row>
{grid}
</Row>
</Grid>
);
}
}
function mapStateToProps(state) {
return {
products: state.products
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ updateBasket: updateBasket }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Products);
和子组件代码:
export default class GridLayout extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0,
}
this.handleAdd = this.handleAdd.bind(this);
}
handleAdd(product) {
this.setState({counter: this.state.counter + 1}, () => {
var counter = this.state.counter
console.log('counter is' + counter)
this.props.addProductToBasket(product, counter);
});
}
render() {
return(
<Col xs={12} md={4}>
<div style={{padding: '10px', backgroundColor: 'white', height: '120px', width: '100%'}}>
<div>{this.props.id}</div>
<div>{this.props.name}</div>
<div>{this.props.description}</div>
<div>$ {this.props.price}</div>
<div style={{float: 'right', cursor: 'pointer'}} onClick={this.handleAdd}>
+
</div>
</div>
</Col>
);
}
}