T
T
TjLink2018-10-28 16:25:00
JavaScript
TjLink, 2018-10-28 16:25:00

React.js Doesn't update content on site when adding element to array. Why?

I'm making a simple React.js ToDo with a filter
. When I click on "OK", a new element is added to the "users" array.
But the site is not updated and the new element does not appear.
It appears only when I start writing a name in the search bar, then I erase everything and then it appears
Why and how to fix it?

var users = [
  {
    id : 1,
    name : 'Piter',
    done : false
  },
  {
    id : 2,
    name : 'Mikle',
    done : true
  }
  ]


  class Search extends React.Component{
    state = {
    }
    change = (e) => {
      var newText = e.target.value.trim();
      this.props.filter(newText);
    }
    render(){
      return (
        <div>
          <input type="text" onChange={this.change} />
        </div>
      )
    }
  }




  class Item extends React.Component {
    state = {
    }
    render(){
      return <h1>{this.props.data.name}</h1>
    }
  }



  class App extends React.Component {
    state = {
      people : this.props.data
    }
    filterList = (newText) =>{
      var newMass = this.props.data.filter(function(user){
        return (user.name).toLowerCase().search(newText.toLowerCase()) !== -1;
      })
      this.setState({people : newMass})
    }
      press = () => {
      users.push({id: 3, name: 'Hello', done: false})
      console.log(users);
    }
    render(){
      return(
        <div className="mainBlock">
        <button type="submit" onClick={this.press}> OK </button>
        <Search filter={this.filterList}/>
          {
            this.state.people.map(function(user){
              return <Item key={user.id} data={user} />
            })
          }
        </div>
      )
    }
  }
  ReactDOM.render(<App data={users}/>, document.getElementById('root'))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dasha Tsiklauri, 2018-10-28
@TjLink

because you are adding to the users array , which is not a property inside state . Accordingly, your state does not change, so the react does not update the component, you need to change the state .
this.state.people.push() // пушить сюда

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question