作者:gl君 | 来源:互联网 | 2022-12-06 20:07
我正在尝试创建一个功能,当用户单击添加按钮时className = "addButton"
; 他们将添加从父类中获取的.json获得的价格值this.props.products
.
我的问题是>当我尝试渲染包含添加按钮的ProductSquare组件以及与产品相关的一些其他内容时,它将呈现无限循环.
我也选择性地瞄准具有独特性的产品 product._id
import React, { Component } from "react";
//css classes
import "./cssForComponents/ProductSquare.css";
import AddButton from "./addButton.js";
class ProductSquare extends Component {
constructor(props) {
super(props);
this.state = {
isLoaded: true,
sum: 0
};
this.OnClickHandlerForAdd= this.onClickHandlerForAdd.bind(this);
this.getData = this.getData.bind(this);
}
onClickHandlerForAdd(price) {
this.setState({ sum: price });
}
getData() {
return this.props.products.map(
(product) =>
product._id === "5b77587c570ee12e768704da" ? (
) : (
console.log("Results were not loaded")
)
);
}
render() {
console.log(this.state.sum);
return this.getData();
}
}
export default ProductSquare;
1> 小智..:
在进行渲染时,实际上正在调用 onClick处理程序; 因此国家正在改变,因此另一个渲染等.它应该是:
OnClick={() => this.onClickHandlerForAdd(product.price)}
这样onClick处理程序就会注册一个单击时要调用的函数