我正在尝试在 React 中操作一个简单的道具,但它给了我一个错误
I'm trying to manipulate a simple props in React but it gives me an error
let num = arr.filter(item => item == n).length;
if(num < this.props.amount){
return alert(`${this.state.number} has had ${++num} drinks`);
//line below is the manipulation of props issue
}else if( num == this.props.amount - 1){
return alert(`${this.state.number} has had ${this.state.number}, cut them off`);
}else if( num > this.props.amount){
return alert(`${this.state.number} is all done drinking`)
}
我只是从父组件传递一个简单的道具。我期待 6 个,我收到了 6 个作为道具。但是当我试图做到这一点时,基于零的数组系统不会影响一个人可以喝的酒量,我不能使用运算符从道具中减去一个,所以基本上数组将从 1 开始.
听起来像this.props.amount
是一个字符串,你需要它是一个整数才能执行"minus"算术运算。其他情况不会抛出错误,因为在 js 中 >
运算符对字符串和整数都有效。
正确的解决方案是确保道具的类型 integer.You 也可以像这样将字符串转换为整数:parseInt("10")
。可能是这样的:
const amount = parseInt(this.props.amount)
if(num < amount){
return alert(`${this.state.number} has had ${++num} drinks`);
}else if( num == amount - 1){
return alert(`${this.state.number} has had ${this.state.number}, cut them off`);
}else if( num > amount){
return alert(`${this.state.number} is all done drinking`)
}
let num = arr.filter(item => item == n).length;
if(num < this.props.amount){
return alert(`${this.state.number} has had ${++num} drinks`);
//line below is the manipulation of props issue
}else if( num == this.props.amount - 1){
return alert(`${this.state.number} has had ${this.state.number}, cut them off`);
}else if( num > this.props.amount){
return alert(`${this.state.number} is all done drinking`)
}
我只是从父组件传递一个简单的道具。我期待 6 个,我收到了 6 个作为道具。但是当我试图做到这一点时,基于零的数组系统不会影响一个人可以喝的酒量,我不能使用运算符从道具中减去一个,所以基本上数组将从 1 开始.
听起来像this.props.amount
是一个字符串,你需要它是一个整数才能执行"minus"算术运算。其他情况不会抛出错误,因为在 js 中 >
运算符对字符串和整数都有效。
正确的解决方案是确保道具的类型 integer.You 也可以像这样将字符串转换为整数:parseInt("10")
。可能是这样的:
const amount = parseInt(this.props.amount)
if(num < amount){
return alert(`${this.state.number} has had ${++num} drinks`);
}else if( num == amount - 1){
return alert(`${this.state.number} has had ${this.state.number}, cut them off`);
}else if( num > amount){
return alert(`${this.state.number} is all done drinking`)
}