【问题标题】:using array.findIndex() on state in React在 React 中对状态使用 array.findIndex()
【发布时间】:2017-09-22 15:28:53
【问题描述】:

所以我是新来的反应,我需要一些帮助。我正在研究一个接受多个值的表单,目前正在测试一个函数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() 来检查它。当我查看控制台输出时,我没有得到符合情况的输出。

提前致谢,

【问题讨论】:

    标签: javascript arrays reactjs filtering state


    【解决方案1】:

    你用错了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]] }})
    

    完全不可读。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-14
      • 2018-12-24
      • 2020-02-27
      • 2016-08-31
      • 2017-09-19
      • 2021-04-16
      • 1970-01-01
      相关资源
      最近更新 更多