Answer the question
In order to leave comments, you need to log in
React.js, why isn't the array updated the first time?
Hello, I can’t understand what’s wrong, I’m trying to make a simple ToDo list , consisting of an input field, a button and elements. After pressing the button, the information from the input field is pushed (.push(...)) into an initially empty array, then this array is copied to the state and then displayed as an element. The problem is that after trying to add the first task, nothing is displayed, but when adding the second, everything starts working fine, while the first one also appears
import React from 'react';
class AddItems extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue: '',
items: []
};
this.inputChange = this.inputChange.bind(this);
this.addNewItem = this.addNewItem.bind(this);
this.arrOfItems = [];
this.showItems = this.showItems.bind(this);
this.arrOfLiElements = [];
}
inputChange(event){
this.setState({inputValue: event.target.value});
}
addNewItem(){
//если инпут пустой то return
if (this.state.inputValue === '') return;
//добавление нового элемента в массив
this.arrOfItems.push({
text: this.state.inputValue,
id: (new Date()).getTime().toString()
});
//обновление состояния (обновление массива с элементами, сброс инпута)
this.setState({
items: this.arrOfItems,
inputValue: ''
});
console.log(this.arrOfItems); //все элементы на месте
console.log(this.state.items); // при первом вызове пустой, потом всё нормально
//переделываем обычный массив в массив li элементов
this.showItems();
}
showItems() {
this.arrOfLiElements = this.state.items.map((item) => <li key={item.id}>{item.text}</li>)
}
render() {
return (
<div className="addItems">
<div className="addSection">
<input type="text" value={this.state.inputValue} onChange={this.inputChange}/>
<input type="submit" onClick={this.addNewItem}/>
</div>
<div className="listSection">
<ul>{this.arrOfLiElements}</ul>
</div>
</div>
)
}
}
export default AddItems;
Answer the question
In order to leave comments, you need to log in
Can anyone suggest why this is happening and how to fix it?
class AddItems extends React.Component {
state = {
value: '',
items: []
}
inputChange = ({ target: { value } }) => {
this.setState({ value });
}
addNewItem = () => {
if (this.state.value) {
this.setState({
items: [ ...this.state.items, {
text: this.state.value,
id: (new Date()).getTime().toString()
} ],
value: ''
});
}
}
render() {
return (
<div className="addItems">
<div className="addSection">
<input type="text" value={this.state.value} onChange={this.inputChange} />
<input type="submit" onClick={this.addNewItem} />
</div>
<div className="listSection">
<ul>{this.state.items.map((item) => <li key={item.id}>{item.text}</li>)}</ul>
</div>
</div>
)
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question