在React中使用array.findIndex()on state

时间:2017-09-22 15:28:53

标签: javascript arrays reactjs filtering state

所以我是新手做出反应,我需要一些帮助。我正在处理一个接受多个值的表单,我正在测试一个函数assignAtribute,它接受​​输入元素的名称并使用它来更新名为currentRecipe的数组的状态(请参阅下文)。

 assignAttribute = (ident) => {
    var x = document.getElementById(ident).name;
    var holder = this.state.currentRecipe;
    var temp = null;

    var check = holder[x].findIndex(() => {return this.state[x]});

    check == -1 ? console.log('ok') : console.log('already exists')

    console.log(check)

    x == 'title' ?  temp = update(holder, {[x]: {$set: this.state[x] }}) 
    : x == 'ingredients' ? temp = update(holder, {[x]: {$push: [this.state[x]] }}) 
    : temp = update(holder, {[x]: {$push: [this.state[x]] }})

    holder = temp
    this.setState({ currentRecipe: holder})
    console.log(this.state[x])
    console.log(holder[x])

}

我遇到了问题:

我想过滤输入,所以没有重复项,所以我使用的是一个使用array.findIndex()来检查它的函数。当我查看控制台输出时,我没有得到符合情况的输出。

提前致谢,

1 个答案:

答案 0 :(得分:0)

您使用Array.prototype.findIndex错误。 而不是:

var check = holder[x].findIndex(() => {return this.state[x]})

它应该是:

var check = holder[x].findIndex(el => el === this.state[x])

除此之外,我需要一个更好的背景。我不知道holder变量的结构是什么,这个:

x == 'title' ?  temp = update(holder, {[x]: {$set: this.state[x] }}) 
    : x == 'ingredients' ? temp = update(holder, {[x]: {$push: [this.state[x]] }}) 
    : temp = update(holder, {[x]: {$push: [this.state[x]] }})

完全不可读。