【问题标题】:lodash _.pullAt returning undefined at pathlodash _.pullAt 在路径返回未定义
【发布时间】:2017-07-11 18:24:50
【问题描述】:

我在 react 应用程序中使用 lodash 来更新和删除数组中的嵌套元素,该数组包含随后更新我的组件状态并保存到 localStorage 的对象。

 questions = [{"question":"","type":"text","conditions":null,"isSub":false,"subQ":[]}]
 path = '[0]'

    //returns [undefined x 1]
function deleteQuestion(path){  
   const { questions } = this.state
   _.pullAt(questions, path)
  this.setState({questions: questions})
}

我是 lodash 新手,但是通过路径删除元素而不返回 null 或 undefined 的最佳方法是什么?

【问题讨论】:

    标签: javascript arrays reactjs lodash


    【解决方案1】:

    _.pullAt 接受整数,而不是字符串

    _.pullAt(questions, 0)  
    console.log(questions)  // output is []
    

    【讨论】:

    • 如果我要删除问题[0].subQ[0] 中的孩子怎么办?我该怎么做?我在 React 中有一个表单构建器,并为每个孩子附加了一个与其在问题中的位置相对应的路径属性。这就是我使用 ._set 更新输入的方式。
    • 用您的数组替换questions,在本例中为questions[0].subQ
    猜你喜欢
    • 2017-06-16
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 2016-08-22
    • 1970-01-01
    • 2011-01-08
    相关资源
    最近更新 更多