首页 > 解决方案 > React TypeError:“这是未定义的”,函数调用中的函数不起作用

问题描述

试图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;

标签: reactjs

解决方案


您在.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 })
  }

推荐阅读