T
T
TheGhost9022018-07-29 15:52:58
HTML
TheGhost902, 2018-07-29 15:52:58

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;

Can anyone suggest why this is happening and how to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-07-29
@TheGhost902

Can anyone suggest why this is happening and how to fix it?

It doesn't make much sense to answer the question "why" - you are doing some kind of nonsense, all these additional arrays, who taught you these nonsense?
How to fix it - yes, throw everything superfluous to hell, leave one items array, and work with 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 question

Ask a Question

731 491 924 answers to any question