+ 5
Cannot set property setState of undefined
Why is there an error? Text is part of the class state yet when changing it apparently it doesn't even exist. The error appears when you type in the input field Am I even doing this thing right? Will this make a todo list?! I can't even do the basics right. https://code.sololearn.com/WYAiaEKoSqRy/?ref=app
15 Respuestas
+ 3
Clueless Coder I think you didn't bind the event function correctly
Try
this.handleChange = this.handleChange.bind(this)
+ 4
Calviղ Thanks!
+ 3
Clueless Coder “Cannot set property setState of undefined” means that this is undefined. I’ll play around a bit...
+ 3
Calviղ Do you have any tips for this? I have no idea how to make this. Everytime I try something it gets messed up.
How do I add a list element with the input value on button press?
+ 3
Clueless Coder
Rowsej have made the item updated.
Maybe you can consider update the state of list items using setState,
this.setState({list: [...this.state.list, this.state.text]});
+ 3
And not to forget to add attribute key with unique value on each of the li items
+ 3
Calviղ Thanks. I'll need to look into this as I don't get the spread operator and key attribute. I'll do some research
+ 3
Clueless Coder I modified Rowsej's code further.
Please check it out
https://code.sololearn.com/W6U106y6G234/?ref=app
Rowsej I think list has to be updated with setState.
+ 3
Clueless Coder This article should make you more understand on list item populating and the use of key attribute
https://reactjs.org/docs/lists-and-keys.html
Spread oparator helps us write cleaner codes,
If you still not understand spread operator, study this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
+ 3
Hey, if you don't wanna bind each function that you make, just use arrow functions.
handleChange = () => {
}
You can add an item by using an onSubmit function on a button:
this.setState({
todos: [...this.state.todos, newTodo]
})
Spread operator means "all the elements inside todos array, and then add the newTodo at the end.
+ 2
Ahh yes Calviղ, you’re right. I had forgotten about function.bind() altogether! That makes lots of sense.
+ 2
Calviղ Thanks. I really need to learn more, I would never have got this by myself
+ 1
Clueless Coder First, you’ll have to do the this.addItem = this.addItem.bind(this) in the constructor. Look at line 49 in this: https://code.sololearn.com/W3WlLL8z2Uc0/?ref=app
Please note: I’m not a React pro, Calviղ will be better telling you how to make the DOM update/render after adding something; right now you have to type something again for it to update.