将两个道具从父组件传递给子组件会导致父组件未定义
Posted
技术标签:
【中文标题】将两个道具从父组件传递给子组件会导致父组件未定义【英文标题】:Passing two props from parent to child component leads to undefined in parent 【发布时间】:2018-06-24 03:04:21 【问题描述】:在我的 react redux 项目中,我试图将 props 从子组件传递到父组件。更具体地说,我想将两条信息:产品和计数器传递给父容器,这两条信息都打算在函数内部使用,如下所示:
addProductToBasket(product, counter)
我的问题是:在 addProductToBasket 函数中无法识别计数器,我收到以下错误消息:
未捕获的引用错误:未定义计数器
为什么这里没有定义计数器,如何在这个函数中正确使用它?
这里是相关的父容器代码:
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>
);
【问题讨论】:
【参考方案1】:这是因为您忘记在箭头函数中接收从父组件内部的子组件传递的参数。
这里:
addProductToBasket=() => this.addProductToBasket(product, counter)
使用这个:
addProductToBasket=(prodt, counter) => this.addProductToBasket(prodt, counter)
原因是:您没有将addProductToBasket
直接传递给孩子,而是在传递arrow function,并且在箭头函数体内调用@ 987654325@,所以你需要在箭头函数中接收参数并将这些参数传递给addProductToBasket。
其他可能的解决方案是:
去掉箭头函数,这样写:
addProductToBasket= this.addProductToBasket
【讨论】:
遇到任何问题?【参考方案2】:替换这一行:
addProductToBasket=() => this.addProductToBasket(product, counter)
有了这个:
addProductToBasket=this.addProductToBasket.bind(this, product, counter)
【讨论】:
以上是关于将两个道具从父组件传递给子组件会导致父组件未定义的主要内容,如果未能解决你的问题,请参考以下文章