Update array in React

7

Having the following code,

this.state = { 
        valores: ['A', 'B', 'C']
}

How could I update an element in this array? Of the type:

this.setState({
    valores[1]: 'a'
})
    
asked by XXx 24.11.2016 в 19:27
source

2 answers

7

I recommend not to directly mutate the state object, instead assign it to a variable and reassign it.

Here you can read some reasons why you should not mutate directly link

You could also use link

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this)
    this.state = {
      valores: ['a', 'b', 'c']
    };
  }
  
 handleClick(e) {
    e.preventDefault();
    var valores = this.state.valores;
    valores[0] = Math.random();
    this.setState({valores: valores});
  }
 
  render() {
    return (
      <div>
        <div>{this.state.valores}</div>
        <button onClick={this.handleClick}>Cambiar primer valor</button>
      </div>
    );
  }
};

ReactDOM.render(
  <MyComponent />,
  document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
    
answered by 24.11.2016 / 21:35
source
1

It is not advisable to use auxiliary variables because in components that handle a more complex state it is unmanageable to change the state in this way, for this React provides Helpers that help you to mutate the state when its structure becomes more complex

link

Thus, for example, assuming that your component handles more variables in the state than part of 'values', using React Inmutability Helpers, the implementation would be the following (ES6)

import React from 'react'
import update from 'react-addons-update'

export default class ValoresComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            valores: ['A', 'B', 'C'],
            otrosValores: {
                objetoAdicional: {
                    attr: false,
                    attr1: 1
                }
            }
        }
    }

    agregarD = () => {
        this.setState(update(
            this.state, { valores: {$push: 'D'} }
        ))
    };

    render() {
        return(
            <div>
                <div>{this.state.valores}</div>
                <button onClick={this.agregarD}>Agregar D</button>
            </div>
        )
    }
}

In this way you update only the 'values' array and leave the rest of the state structure intact without the need to make unnecessary copies or use auxiliary variables.

    
answered by 28.12.2016 в 02:36