JavaScript React Basics (retired) Designing Data Flow Communicating Events

How to change/update state when using es6 class component and not react.create class

I get this note in the console "Do not mutate state directly. Use setState()", if am to use setState how do i select just the score property of the player object

William, Do you have an example of where you are getting the error? Consider the second example under State Updates May Be Asynchronous

this.setState(prevState =>({
    players: prevState.players[index].score += delta,
}))

2 Answers

Mike Jensen
Mike Jensen
11,718 Points

Using react version 16 with ES6, I used this solution:

  onScoreChange(index, delta) {
    const player = [...this.state.players][index]

    player.score += delta
    this.setState(player)
  }
Dimang Chou
Dimang Chou
4,697 Points

import React, { } from 'react'; class Players extends React.Component { constructor (props) { super(props); this.state = { data: [ { name: "Josh", score: 32, id: 1 }, { name: "Endy", score: 25, id: 2 }, { name: "Dimang chou", score: 39, id: 3 } ] }; }

onScoreChange = (val, key) => {
    // console.log(key);
    var data = this.state.data;
    data[key].score += val;
    this.setState(function () {
        return {
            data: data
        }
    });
}

render(){
    return (
        <div className="players">
            {this.state.data.map(function (player, i) {
                return (
                    <Player
                        onScoreChange={function(val) {this.onScoreChange(val, i)}.bind(this)}
                        key={i}
                        data={player} />
                );
            },this)}
        </div>

    );
}

}

Players.PropTypes = { name : React.PropTypes.string, score : React.PropTypes.number, data: [] // methods };

class Player extends React.Component { constructor(props){ super(props); this.state = { score : props.data.score } }

render() {
    return (
        <div className="player">
            <div className="player-name">
                {this.props.data.name}
            </div>
            <div className="player-score">
                <div className="counter">
                    <button className="counter-action decrement"  onClick={function () {
                        this.props.onScoreChange(-1);
                    }.bind(this)}> - </button>
                    <div className="counter-score"> {this.props.data.score} </div>
                    <button className="counter-action increment" onClick={function () {
                        this.props.onScoreChange(1);
                    }.bind(this)}> + </button>
                </div>
            </div>
        </div>
    );
}

}

// this.props Player.PropTypes = { onScoreChange: React.PropTypes.func };

export default Players;