反应TypeError:“这是未定义的”,函数调用内的函数不起作用

时间:2019-05-31 12:53:06

标签: reactjs

试图在addChildNodeNext函数中调用addChildNode方法,但是

result = this.addChildNodeNext(item.childrens,CurrentID)

给出错误this is undefined。我已经在构造函数中绑定了这两个函数。

class TestAdd extends Component {
  constructor(props) {
    super(props)
    this.addChildNode = this.addChildNode.bind(this)
    this.addChildNodeNext = this.addChildNodeNext.bind(this)
  }

  addChildNodeNext = (nodeList, CurrentID) => {
    alert(`Self ${nodeList} : ${CurrentID}`)
    return nodeList
  }

  addChildNode = (nodeList, CurrentID) => {
    const { childIndex } = this.state
    let index = childIndex
    const newTree = nodeList.filter(function (item) {
      alert(`Self ${item.name} : ${CurrentID}`)
      index += 1
      let result = ""
      if (item.name === CurrentID) {
        const newName = `child_${childIndex}_${CurrentID}`
        result = item.childrens.push({ name: newName, parent: newName, childrens: [] })
      } else if (item.childrens.length > 0) {
        result = this.addChildNodeNext(item.childrens, CurrentID)
      } else {
        result = item
      }
      return result
    });
    this.setState({ childIndex: index })
    this.setState({ treeNode: newTree })
  }

}

export default TestAdd;

1 个答案:

答案 0 :(得分:0)

您正在.filter方法中使用常规函数。这就是为什么您在那里丢失this上下文的原因。另外,您不需要在构造函数中绑定函数,因为您使用的是箭头函数。

addChildNode = (nodeList, CurrentID) => {
    const { childIndex } = this.state
    let index = childIndex
    const newTree = nodeList.filter(function (item) { // <--- HERE
      alert(`Self ${item.name} : ${CurrentID}`)
      index += 1
      let result = ""
      if (item.name === CurrentID) {
        const newName = `child_${childIndex}_${CurrentID}`
        result = item.childrens.push({ name: newName, parent: newName, childrens: [] })
      } else if (item.childrens.length > 0) {
        result = this.addChildNodeNext(item.childrens, CurrentID)
      } else {
        result = item
      }
      return result
    });
    this.setState({ childIndex: index })
    this.setState({ treeNode: newTree })
  }

您可以将其替换为箭头功能:

addChildNode = (nodeList, CurrentID) => {
    const { childIndex } = this.state
    let index = childIndex
    const newTree = nodeList.filter(item => {
      alert(`Self ${item.name} : ${CurrentID}`)
      index += 1
      let result = ""
      if (item.name === CurrentID) {
        const newName = `child_${childIndex}_${CurrentID}`
        result = item.childrens.push({ name: newName, parent: newName, childrens: [] })
      } else if (item.childrens.length > 0) {
        result = this.addChildNodeNext(item.childrens, CurrentID)
      } else {
        result = item
      }
      return result
    });
    this.setState({ childIndex: index })
    this.setState({ treeNode: newTree })
  }