Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/362.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
Javascript Reactjs-Can';无法从数组中获取值,未定义_Javascript_Arrays_Reactjs - Fatal编程技术网

Javascript Reactjs-Can';无法从数组中获取值,未定义

Javascript Reactjs-Can';无法从数组中获取值,未定义,javascript,arrays,reactjs,Javascript,Arrays,Reactjs,我试图比较两个状态数组的值,但是当我查看otherItems[I]的值时,我得到了未定义的值。为了澄清,Items是一个包含许多数据点的对象数组,为什么我用.name来调用它,而otherItems只是一个名称数组。如果我只调用this.state.otherItems,那么我将得到完整的数组内容 this.state = { Items: [], otherItems: [], ... } ... function = () => { var total = this.s

我试图比较两个状态数组的值,但是当我查看
otherItems[I]
的值时,我得到了
未定义的值。为了澄清,
Items
是一个包含许多数据点的对象数组,为什么我用
.name
来调用它,而
otherItems
只是一个名称数组。如果我只调用
this.state.otherItems
,那么我将得到完整的数组内容

this.state = {
  Items: [],
  otherItems: [],
  ...
}
...
function = () => {
  var total = this.state.total;
  var i;
  for(i = 0; i < this.state.Items.length; i++) {
    console.log(this.state.otherItems[i]);
    if(this.state.Items[i].name === this.state.otherItems[i]) {
      total += parseFloat(this.state.Items[i].price)
    }
  }
  this.setState({Total: total})
}
this.state={
项目:[],
其他项目:[],
...
}
...
函数=()=>{
var total=this.state.total;
var i;
对于(i=0;i

我想做的是比较两个数组中的项目,并且只有当且仅当
items
中的项目
I
存在于
otherItems
中时,才将项目的价格添加到总金额中

您正在使用循环变量
i
,并使用该变量对两个数组进行索引,因此您只是在比较两个数组之间具有相同索引的元素,并且两个数组的长度可能不同

您可以改为使用检查
Items
中元素的
名称是否存在于
otherItems
数组中

getTotal() {
  this.setState(({ total = 0, Items, otherItems }) => {
    Items.forEach(item => {
      if (this.state.otherItems.includes(item.name)) {
        total += parseFloat(item.price);
      }
    });

    return { otherTotal: total };
  });
}

您正在记录
basketItems[i]
,而不是
otherItems[i]
。这就是你所说的给你未定义的东西吗?@Tholle啊,对不起,那是一种类型,应该是其他项目。我现在修复了它。您在
console.log(this.state.otehrItems[I])中有一个输入错误
应该是
console.log(this.state.otherItems[i])好的。你能澄清一下你想要完成的是什么吗?请提供一个答案,因为这将使帮助您的人更容易。@NilsKähler是的,这是我在编辑时犯的另一个错误。使用prevState实现了一个非常好的答案,以避免异步冲突。我尝试了这一点,但出于一些奇怪的原因,
total
返回为
NaN
不是数字
@taway0282好的。你能在问题中包括所有相关代码吗?它可能被称为
Total
,而不是
Total
,或者当前代码没有显示的其他内容。如果存在任何小的不一致,例如
Total
而不是
Total
,这不是实际问题,只是转录错误。在代码编辑器中,它是正确的变量名。这对一些小的调整起到了作用,非常感谢:)我应该将调整后的版本作为一个编辑发布,还是应该怎么做?