Home > Software design >  integer value not changing from function in React
integer value not changing from function in React

Time:07-26

image here Hi I am trying to get my click Power variable to double when function Upgrade is called however nothing is happening. Can anyone tell me why?

CodePudding user response:

You need to make it this.clickPower *= 2 (in the Upgrade function), with the equals in order to alter the value of the variable.

CodePudding user response:

You forgot to set an equal. The upgrade return is going nowhere, because upgrade is used as an onClick callback.

Using this.clickPower is not a good idea. If you want to initialize it in the render function, because it is not a props, state or ref.

React is rerendering following props and state, so you should set your clickPower in a state if you want to use it properly.

You should better initialize upgrade out of the render function.


// Not event callback mode : 
let clickPower = 1;

function upgrade(value) => {
   return value * 2;
}

clickPower = upgrade(clickPower);

// As callback but not in a React App
this.clickPower = 1;

function upgrade(e) => {
   this.clickPower *= 2;
}

// Good way
constructor(props) {
    super(props);

    this.state = { clickPower: 1 };
}

function upgrade(e) => {
   this.setState({ clickPower: this.state.clickPower * 2});
}

Plus :

const { money, setMoney } = this.props;
  • Related