我试图在React中操纵一个简单的道具,但它给了我一个错误

时间:2018-03-30 17:54:01

标签: javascript reactjs operators

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.

1 个答案:

答案 0 :(得分:0)

听起来像this.props.amount是一个字符串,你需要它是一个整数来执行&#34;减去&#34;算术运算。其他情况不会抛出错误,因为在js >运算符对字符串和整数都有效。

然后正确的解决方案是确保props类型为integer。您也可以将字符串转换为整数,如下所示: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`)
}