繁体   English   中英

我正在尝试在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是一个字符串,您需要将其作为整数来执行“减”算术运算。 其他情况不会引发错误,因为在js >运算符中,字符串和整数均有效。

正确的解决方案是确保props是integer类型。您还可以将字符串转换为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`)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM