简体   繁体   中英

React multiple states reset

I have a bunch of state variables and I separated them instead of making an object. I don't know if this is the right way to go but I have a function that calculates and sets state variables based on a num input state that changes:

  const [isLow, setIsLow] = useState(false);
  const [isMedium, setIsMedium] = useState(false);
  const [isLarge, setIsLarge] = useState(false);
  const [isInfinite, setIsInfinite] = useState(false);

  function handleNum() {
    
    if (num < 120) {
      setIsLow(true);
    } else if (num < 320) {
      setIsMedium(true);
    } else if (num < 600) {
      setIsLarge(true);
    } else if (num >= 600) {
      setIsInfinite(true);
    }

    setCurrentNum(num);
  }

My problem is that is the first num is 9, then I change it to 500. The states isLarge and isLow are both true. I don't want to set every other state to false in each if statement so is there a better way? The only other thing, I can think of, is using an object for state but it doesn't seem right. it feels like it would be expensive. I haven't used reducers before but would this be a good case to use one?

If isLow , isMedium , etc are always exclusively dependent on the value of num , then you don't need to use state for those variables. You can just assign them directly in the body of the function component.

const isLow = (num < 120);
const isMedium = (mum >= 120 && num < 320);
const isLarge = (num >= 320 && num < 600);
const isLarge = (num >= 600);

you can use multiple states but it would become complex as your application grows.

while using your approach, what I would do is when setting one state to true, I would set other states to false.

const [isLow, setIsLow] = useState(false);
const [isMedium, setIsMedium] = useState(false);
const [isLarge, setIsLarge] = useState(false);
const [isInfinite, setIsInfinite] = useState(false);
    
function handleNum() {
        
if (num < 120) {
  setIsLow(true);
  setIsMedium(false);
  setIsLarge(false);
} else if (num < 320) {
  setIsMedium(true);
  setIsLow(false);
  setIsHigh(false);
} else if (num < 600) {
  setIsLarge(true);
  setIsLow(false);
  setIsMedium(false);
} else if (num >= 600) {
  setIsInfinite(true);
  setIsLow(false);
  setIsMedium(false);
  setIsLarge(false);
}
   
  setCurrentNum(num);
}

Like this.

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