1

I am new in React.js, I am designing a little game.

When I am setting the life value, I want to use the value of job, can I do it in React.js?

Here is part of my code:

this.setState({
            players:[
                {
                    id:uuid.v4(),
                    name: "A",
                    job: "Wizard",
                    life: this.getRandHealth("Wizard")
                }, {
                    id:uuid.v4(),
                    name: "B",
                    job: "Witch",
                    life: this.getRandHealth("Witch")
                }]});

I want directly access job instead of signing them manually. Can I do it?

Ilona
  • 357
  • 3
  • 10
Shukai Ni
  • 457
  • 2
  • 6
  • 17
  • When will the code above be called? If `this.getRandHealth` will update the health as well, you don't have to list the other parameters, but just change life. – Björn Böing Jun 14 '17 at 10:13

1 Answers1

0

A solution is to define the players list without the life and then use .map() to add it:

var list = [{
  id: uuid.v4(),
  name: "A",
  job: "Wizard",
}, {
  id: uuid.v4(),
  name: "B",
  job: "Witch",
}];

this.setState({
  players: list.map(function(obj) {
    return {
      id: obj.id,
      name: obj.name,
      job: obj.job,
      life: this.getRandHealth(obj.job)
    };
  }, this);
});

If the id is always uuid.v4() then you can move that into the map as well and reduce the repetition further.

MrCode
  • 63,975
  • 10
  • 90
  • 112
  • It seems the generated state will be refreshed after I submit a form, could you please look at this? https://stackoverflow.com/questions/44545184/react-js-initial-state-generated-randomly-how-to-prevent-it-from-regenerate-e – Shukai Ni Jun 14 '17 at 12:46