试图在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;
答案 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 })
}