Change attribute of an array of objects in the state in the application

1

To try to make an attribute of one of the objects in an array of objects switch between true and false follow code:

Initial status:

constructor(props) {
    super(props)

    this.state = {
        post: [{
            nome: '',
            conteudo: '',
            comment: false
        }]
    }
    this.handleClickComment = this.handleClickComment.bind(this)

}

Method that changes the comment attribute for each object in the array (corrected):

handleClickComment(postagem) {
    postagem.comment = !postagem.comment
    let i = postagem.id -1
    this.setState({...this.state.post[this.state.post[i] = postagem]})
}

This method is calling in an onClick event, and takes as parameter the object in question as mapped in another component, but whenever the event the comment attribute simply does not change. Could anyone tell me what's wrong?

Edit

I was able to solve the problem of updating the code that worked perfectly, updated the value of the attribute without changing the state of the application directly, always instantiate a new array with the new parameters. Thank you all for the help.

    
asked by anonymous 17.07.2018 / 15:55

1 answer

1

I decided to make a minimal example to change in a list:

class ListApp extends React.Component {
  constructor(props) {
      super(props);
  }
  render() {
      return (
        <div key={this.props.indice}>{this.props.nome} <button type="button" onClick={this.props.click}>Comment - {this.props.comment ? "Verdadeiro": "Falso"}</button></div>
      )
  }
}
class App extends React.Component {
    constructor() {
      super();
      this.state = {
        post: [{
          nome: 'n1',
          conteudo: '',
          comment: false
        },
        {
          nome: 'n2',
          conteudo: '',
          comment: true
        }]
      }            
    }
    
    render() {
      return (<div>{     
          this.state.post.map((m,i) => <ListApp key={i} indice={i} comment={m.comment} nome={m.nome} click={this.handleClickComment.bind(this, i, m)} />)
      }</div>)
    }     
    
    handleClickComment(index, model) {
        model.comment = !model.comment;
        this.state.post[index] = model;
        this.setState({post:this.state.post});        
    }
}

ReactDOM.render(<App/>,document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"crossorigin></script><scriptcrossoriginsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="root"></div>
    
17.07.2018 / 18:33