Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs React中For循环的和数_Reactjs - Fatal编程技术网

Reactjs React中For循环的和数

Reactjs React中For循环的和数,reactjs,Reactjs,我得到了一系列数据,其中包含一个数组(json文件)中的一些对象,它将通过fetch()请求显示。正如您在{this.renderCountETotal(item)}中所看到的,我有一个for循环,我想对for循环中的数字求和,但返回我NaN class App extends React.Component{ constructor(props,context){ super(props,context); this.state={ data:[],

我得到了一系列数据,其中包含一个数组(json文件)中的一些对象,它将通过fetch()请求显示。正如您在
{this.renderCountETotal(item)}
中所看到的,我有一个
for循环
,我想对
for循环
中的数字求和,但返回我
NaN

   class App extends React.Component{
   constructor(props,context){
    super(props,context);
    this.state={
        data:[],
     }
    }
       .
       .
       .
       .
       .
render() {
  const {data} = this.state;
  const renderInvoicesTotal =data.map((item, i) => {
        return   <span>
                    {this.renderCountETotal(item)}
                 </span>
     })
 return (
     <div>
       {renderInvoicesTotal}
  </div>
   )
  }
renderCountETotal(element){
  let lenInfo=element.byproducts.length
  let valueAdded = 0
  for(let i = 0 ; i < lenInfo ; i++){
    let count= parseInt(element.byproducts[i].count)
    valueAdded += count
   }
    valueAdded = parseInt(valueAdded)
    console.log(valueAdded) ////return NaN ////
    return valueAdded
  }
}
ReactDOM.render(<App/>, document.getElementById('Result'))
类应用程序扩展了React.Component{
构造函数(道具、上下文){
超级(道具、背景);
这个州={
数据:[],
}
}
.
.
.
.
.
render(){
const{data}=this.state;
const renderInvoicesTotal=data.map((项目,i)=>{
返回
{this.renderCountETotal(项目)}
})
返回(
{renderInvoicesTotal}
)
}
renderCountETotal(元素){
设lenInfo=element.byproducts.length
设valueAdded=0
for(设i=0;i
尝试将rendercountETotal方法替换为以下方法:

renderCountETotal(element)
   {
  let valueAdded = 0
  let count = 0
  for(let i = 0 ; i < element.byproducts.length ; i++)
  {
    count= parseInt(element.byproducts[i])
    valueAdded += count
  }
    return valueAdded
 }
renderCountETotal(元素)
{
设valueAdded=0
让计数=0
for(设i=0;i
使用
reduce
函数获取聚合计数:-

const getCount = element.reduce((x,y) => x + (y.byproducts || 0));

解析前,
valueAdded
的值是多少。Hi@Kaushik。它是
让valueAdded=0
而不是这个,在
for loop
检查
元素.byproducts[i]。count
值之后。我认为并非所有产品都提供
element.byproducts[I].count
。因为
parseInt(undefined+number)=>NaN
。不进行检查,而是执行以下操作:
parseInt(element.byproducts[i].count | | 0),然后检查结果。