【发布时间】:2020-04-01 23:27:32
【问题描述】:
我正在尝试使用一个函数将商品从详细信息页面添加到购物车到主 App 组件中的购物车数组。每当加载 Product Detail 组件时,该函数都会运行一次,当我单击“添加到购物车”按钮时,该函数会持续运行,直到 React 停止状态更新。
这是我的 App.js
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
cart: []
};
this.handleAddToCart = this.handleAddToCart.bind(this);
}
handleAddToCart(product) {
this.setState({
cart: [this.state.cart, product]
});
}
//I'm using React-Router with history.js
render() {
return (
<Router history={history}>
<Switch>
<Route
path="/product/detail"
exact
render={routeProps => (
<ProductDetail {...routeProps} handleAddToCart={this.handleAddToCart} />
)}
/>
</Switch>
</Router>
);
}
}
export default App;
这里是 ProductDetail.js
class ProductDetail extends Component {
constructor(props) {
super(props);
this.state = {
product: {}
};
}
componentDidMount() {
// Getting data from React Router Link
const product = this.props.location.state.product;
this.setState({
product: product
});
}
render() {
const product = this.state.product;
return (
<Link onClick={this.props.handleAddToCart(this.state.product)}>
<Button>
Add to Cart
</Button>
</Link>
)
}
}
基本上,我只希望在单击按钮时运行 handleAddToCart。另外,我将按钮的 onClick 设置为该功能,但它无法正常工作
【问题讨论】:
-
可能不相关,但您应该在旧的购物车状态数组中传播:
this.setState({ cart:[...this.state.cart, product] })
标签: javascript reactjs react-router