Tuesday 28 February 2017

javascript - React state defind as property deep clone returns 'is undefined'

Answer


Answer





I'm trying to write a simple ToDo app.



Clicking on TodoItem should remove a item from state but when I do this I'm getting a TypeError: this.state is undefined. I don't know what is wrong.



My code looks like this:



---- App.js ----



import React from "react";

import TodoItem from "./components/TodoItem";

class App extends React.Component {
state = {
items: {
item1: { text: "Nazwa item1", isDone: false },
item2: { text: "Nazwa item2", isDone: false },
item3: { text: "Nazwa item3", isDone: false },
item4: { text: "Nazwa item4", isDone: false }
}

};

removeItem(key) {
const items = { ...this.state.items }; // TypeError: this.state is undefined
console.log(items);
}

render() {
return (



    {Object.keys(this.state.items).map(key => (
    removeItem={this.removeItem}
    index={key}
    key={key}
    item={this.state.items[key]}
    />
    ))}



);
}
}

export default App;


---- TodoItem.js ----




import React from "react";

const TodoItem = props => {
return (
  • props.removeItem(props.index)}>
    {props.item.text}
    {props.item.isDone ? "zrobione" : "niezrobione"}

  • );
    };


    export default TodoItem;

    Answer



    The issue is that this is bound to your function and not to the class.



    To prevent that you can use an arrow function to keep the binding of this to the class, or calling .bind method



    That should make it work:




     removeItem = (key) => {
    const items = { ...this.state.items };
    console.log(items);
    }


    or that:



    removeItem={this.removeItem.bind(this)}



    Here is a more in-depth article


    No comments:

    Post a Comment

    c++ - Does curly brackets matter for empty constructor?

    Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...