gpt4 book ai didi

reactjs - 我如何在 React 中解决 "_this is undefined"?

转载 作者:行者123 更新时间:2023-12-02 17:02:13 25 4
gpt4 key购买 nike

正在按照本教程制作一个简单的待办事项应用程序 (https://hackernoon.com/create-a-simple-todo-app-in-react-9bd29054566b)。

事情是我遇到了这个错误:

TypeError: _this is undefined

引用我在以下组件中使用onClick删除时:

import React, {Component} from 'react'

class TodoItems extends Component {

createTasks(item) {
return (
<li key={item.key} onClick={() => this.props.deleteItem(item.key)}>
{item.text}
</li>
)
}
render() {
const todoEntries = this.props.entries
const listItems = todoEntries.map(this.createTasks)

return <ul className="theList">{listItems}</ul>
}
}

export default TodoItems

我已经看到我可能必须在构造函数中使用 .bind(this) 但我不确定如何在此处应用它。

这是 App.js 的片段,其中定义了 deleteItem 并调用了 TodoItems:

    deleteItem = key => {
const filteredItems = this.state.items.filter(item => {
return item.key !== key
})
this.setState({
items: filteredItems,
})
}
inputElement = React.createRef()
render() {
return (
<div className="App">
<TodoList
addItem={this.addItem}
inputElement={this.inputElement}
handleInput={this.handleInput}
currentItem={this.state.currentItem}
/>
<TodoItems entries={this.state.items} deleteItem={this.deleteItem}/>
</div> //App
)
}

在此先感谢您的帮助!

最佳答案

如果你不知道为什么...

The bodies of class declarations and class expressions are executed in strict mode, that is the constructor, static and prototype methods. Getter and setter functions are executed in strict mode.

在 React 的类组件中,当我们像这样将事件处理函数引用作为回调传递时

<button type="button" onClick={this.handleClick}>Click Me</button>

点我事件处理程序方法失去了其隐式绑定(bind)的上下文。当事件发生并调用处理程序时,this 值回退到默认绑定(bind)并设置为 undefined ,因为类声明和原型(prototype)方法在严格模式下运行。

当我们将事件处理程序的 this 绑定(bind)到构造函数中的组件实例时,我们可以将它作为回调传递,而不必担心它会丢失其上下文。

箭头函数不受此行为的影响,因为它们使用词法 this 绑定(bind),自动将它们绑定(bind)到它们定义的范围。

This is why we need to bind event handlers in Class Components in React

Class MDN

关于reactjs - 我如何在 React 中解决 "_this is undefined"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53627803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com