jeudi 30 novembre 2017

Conditional (ternary) Operator to set the state in ReactJS

i am new with Reactjs and doing a game to practice.I want to change the state inside a clickHandler function with a conditional Operator. But don't now if i can do that and my game is not working properly.

clickHandler(){
let tripsOne = Math.round(Math.round((this.state.amountOfGold / this.state.cargoOne) + 0.5))
let hoursOne= (tripsOne*2 + tripsOne*(this.state.distance/this.state.speedOne)).toFixed(2)
let tripsTwo = Math.round(Math.round((this.state.amountOfGold / this.state.cargoTwo) + 0.5))
let hoursTwo= (tripsTwo*2 + tripsTwo*(this.state.distance/this.state.speedTwo)).toFixed(2)
this.setState({tripsOne: tripsOne, hoursOne: hoursOne, tripsTwo: tripsTwo, hoursTwo: hoursTwo, showData: true})
hoursOne < hoursTwo ? this.setState({scoreOne: this.state.scoreOne +1, youWon:true}) : this.setState({scoreTwo: this.state.scoreTwo +1})
}

I need that the last line of this functions works in order to give the victory to the right player.

with console.log i realize that the value of hoursOne(hours player one needs to transport the gold) and hoursTwo is catched and the conditional operator sometimes works in the wrong way.

Feel free to try the game: http://ift.tt/2zQeZrc

When we click Play the winner should be the player who transport the given amount of gold in less time. All the travel is made at same speed and in each trip we need to add 1 hour more to charge the gold and another to descharge.




Aucun commentaire:

Enregistrer un commentaire