Answer the question
In order to leave comments, you need to log in
Why is the array set to null when updating state?
Good afternoon, I can not understand in any way for what reason the null value is written to the array?
I write any words and numbers to the input, it still gives out that the value of the array is null
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
todoValue: ['london']
};
}
render() {
return (
<div className="body-container">
<h1>To Do List</h1>
<input type="text" onKeyDown={this.handleSubmit}/>
<ul>
{this.state.todoValue.map(item => (
<Li text={item}/>
))}
</ul>
</div>
)
}
handleSubmit = (e) => {
if (e.keyCode === 13) {
console.log('success');
this.setState(prevState => ({
todoValue: [...prevState.todoValue, e.target.value]
}));
e.target.value = '';
}
}
}
Answer the question
In order to leave comments, you need to log in
Your array is not equal to null, but at the time of calling the callback passed to setState, SyntheticEvent ceases to exist.
You have two options:
1. Write the value of e.target.value to a variable and pass the variable to the callback:
handleSubmit = e => {
if (e.keyCode === 13) {
const { value } = e.target;
this.setState(prevState => ({
todoValue: [...prevState.todoValue, value],
}));
e.target.value = '';
}
};
handleSubmit = e => {
if (e.keyCode === 13) {
e.persist();
this.setState(
prevState => ({
todoValue: [...prevState.todoValue, e.target.value],
}),
() => {
e.target.value = "";
}
);
}
};
{this.state.todoValue.map((item, index) => (
<Li key={index} text={item} />
))}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question