[英]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:
我不知道这是否是正确的方法,但我有一个函数可以根据更改的 num 输入状态计算和设置状态变量:
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.我的问题是第一个 num 是 9,然后我将其更改为 500。状态 isLarge 和 isLow 都是 true。 I don't want to set every other state to false in each if statement so is there a better way?
我不想在每个 if 语句中将所有其他状态设置为 false 那么有没有更好的方法? 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.如果
isLow
、 isMedium
等总是完全依赖于num
的值,那么您不需要为这些变量使用 state。 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.在使用您的方法时,我会做的是将一种状态设置为 true 时,我会将其他状态设置为 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.像这样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.