简体   繁体   中英

setting state with previous state and regex

I don´t understand how this code works. How does it set the state using the regex? And most importantly, how does it know to set the state using the result variable?

handleClick(evt) {
    const id = evt.target.id;
    const result = evt.target.value;
this.setState(prevState => ({
        value: `${prevState.value}${result}`
          .replace(/([/+\-/*=])([/+\-*=])/g, "$2")
          .replace(/^0+(?=[1-9])/, "")
          .replace(/^0+(?=\.)/, "0")
          .replace(/^0+\B/, "")
      })); 
}

}

So this code do the following:
1. Concatenate prevState.value and evt.target.value into single string (learn more about ES6 Template literals )
2. Replace all combinations like ++ , +- , +* , += , -+ , -- , -* , -= , *+ , *- , ** , *= , =+ , =- , =* , == to it's second character (but I think there is error in the code, replace statement should be ([\\+\\-*=])([\\+\\-*=]) , learn more about regex )
3. Remove from string all number, that start with 0, like 0009 , 01 , etc.
4. Remove all words, that start with 0, like 0a , 0000z , etc.
5. Remove all 0 from string (learn more about \\B )
6. Set result string to the state.value (learn more about React setState() )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM