I have a component in a reactor that describes one task in a Todo application. A task is represented by a <li> element, in which there is text and a delete button in the form of <span> . If you click on <li> , the text should be crossed out. If you click on the <span> with a cross, the entry is deleted.

 import React from "react"; class TodoItem extends React.Component { constructor(props) { super(props); this.state = { text: props.item, done: false }; } render() { let style = this.state.done ? "done" : ""; return ( <li onClick={this.handleComplete} className={style}> {this.state.text} <span className="close" onClick={this.handleRemove}>{"\u00D7"}</span> </li> ); } handleComplete() { this.setState({ done: true }); } handleRemove() { alert("remove"); } }; export default TodoItem; 

When you call the handleComplete() handler, an error occurs in the browser window indicating the line where the component state is updated. What causes this error?

Mistake:

 TypeError: this is undefined handleComplete src/TodoItem.js:24 

Place where component is used:

 import React from "react"; import Todo from "./Todo"; import TodoItem from "./TodoItem"; const List = props => { return ( <ul> { props.items.map((item, index) => <TodoItem item={item} />) } </ul>); }; export default List; 

1 answer 1

handleComplete () loses context. You must either declare the method as a switch function.

 handleComplete = () => {} 

either in the constructor bind context

 this.handleComplete = this.handleComplete.bind(this) 
  • Why does the function lose its context? - typemoon
  • Sorry, it does not lose, it just has a different context, in its "this" method setState is not declared. You need to explicitly specify which context to use - abakan