2

I have this class:

export default class Player {
  constructor() {
    this.scores = [];
  }

 // Insert a new score and keep top N
 insertScore = (score) => {
    this.scores.push(score);
    this.scores.sort((a, b) => b - a);
    if (this.scores.length > N) this.scores.pop();
  };
}

Which is part of a component state:

export default class Menu extends React.PureComponent {
   contructor(props){
     super(props);
     this.state = {
       player: new Player()
     }
   }

   onEndGame(score) {
     player.insertScore(score);
   }
   ...
}

Since changing arrays as part of the state it's very tricky in React (as explained in this aritcle), is the insertScore "legal" in this context?

1 Answer 1

1

You are modifying directly a nested property of the state (this.state.player.scores) so it's not correct.

I'll try this:

Player class

insertScore = (score) => {
    this.scores.push(score);
    this.scores.sort((a, b) => b - a);
    if (this.scores.length > N) this.scores.pop();

    return this;
};

Menu class

onEndGame(score) {
    this.setState({
       player: this.state.player.insertScore(score);
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.