constructor(props){
super(props);
this.state = {productId: '', qty: 0, isCart: true}
}
addToCart = (pid) => (
this.setState((state) => (
{productId: pid, qty: state.qty + 1}
))
);
removeCart = () => (
this.setState({isCart: false})
);
render() {
return(
<div>
<button onClick={() => this.addToCart(1)}>Add to Cart</button>
<button onClick={() => this.addToCart(2)}>Add to Cart</button>
<button onClick={() => this.addToCart(3)}>Add to Cart</button>
<Cart productId = {this.state.productId} qty={this.state.qty} />
</div>
)
}
尝试从父级到子级获取数据时,React Component Lifecycle Methods不能反映数量仍然为0的任何内容。 我不知道为什么要指导。这是代码
谢谢
https://codepen.io/Jack_8588/pen/GbZbZB
答案 0 :(得分:3)
错误名称已经给出了很好的答案,但是我也必须添加它
3 /在购物车类的子组件中使用道具,将this.state.qty
替换为this.props.qty
这是我对Codepen所做的更改:
/*
* A simple React component
*/
class Product extends React.Component {
constructor(props){
super(props);
this.state = {productId: '', qty: 0, isCart: true}
this.addToCart = this.addToCart.bind(this)
this.removeCart = this.removeCart.bind(this)
}
addToCart(pid) {
this.setState({productId: pid, qty: this.state.qty + 1
});
console.log(this.state);
};
removeCart() {
this.setState({isCart: false});
};
render() {
return(
<div>
<button onClick={() => this.addToCart(1)}>Add to Cart</button>
<button onClick={() => this.addToCart(2)}>Add to Cart</button>
<button onClick={() => this.addToCart(3)}>Add to Cart</button>
{ this.state.isCart && <Cart productId = {this.state.productId} qty={this.state.qty} />}
{ ! this.state.isCart && <h3>Cart has been removed</h3>}
<button onClick={this.removeCart}>Remove Cart</button>
</div>
)
}
}
class Cart extends React.Component {
constructor(props){
super(props);
this.state = {qty: this.props.qty}
}
static getDerivedStateFromProps(props, state) {
if(props.qty !== state.qty) {
return {qty: props.qty}
}
return null;
}
componentDidMount() {
console.log('Invoked immediately after component render');
}
shouldComponentUpdate(nextProps, nextState) {
if(this.props.qty !== nextProps.qty) {
return true;
}
return false;
}
componentDidUpdate(prevProps, prevState){
if(this.props.productId !== prevProps.productId){
}
}
componentWillUnmount() {
console.log('component is unmounted and destroyed');
}
render(){
return(
<div>
<h2>Cart Items ({this.props.qty})</h2>
</div>
)
}
}
/*
* Render the above component into the div#app
*/
React.render(<Product />, document.getElementById('app'));
答案 1 :(得分:1)
更新:我错了,请参阅下面的@Brumor答案