【问题标题】:React useState not working with conditional operatorReact useState 不适用于条件运算符
【发布时间】:2020-07-10 17:32:13
【问题描述】:
这是我在 React 中的代码。
const [click, setClick] = useState(false);
const [like, setLike] = useState(dataObj.likedCount); // like === 4
const onClick = () => {
console.log(like);
console.log(click);
return setClick(!click) ? setLike(like - 1) : setLike(like + 1);
};
return (
<Like onClick={onClick}>{like}</Like>
)
这是控制台页面。
我的问题是“喜欢的数字”只会增加,不会减少。
即使布尔值在变化,真到假。
我在我的代码上找不到任何问题.... :((
【问题讨论】:
标签:
javascript
reactjs
conditional-operator
【解决方案1】:
您正在使用setClick 的返回值。 useState 的 setter 函数没有记录的返回值。实验表明它总是返回undefined。所以你不能依赖setClick的返回值。
如果您的目标是使用!click 的值,请直接这样做:
setClick(!click);
if (!click) {
setLike(like - 1); // Or you may want + 1 here
} else {
setLike(like + 1); // Or you may want - 1 here
}
或
setClick(!click);
setLike(like + (click ? 1 : -1)); // Again, you may want to swap 1 and -1,
// depending on whether you want to use the
// old value or the new one
【解决方案2】:
一些注意点:
- 使用状态而不是
setClick(!click) 作为条件运算符
- 不要在
onClick()返回,使用props value(勾选)使其完全可控
const [click, setClick] = useState(false);
const [like, setLike] = useState(dataObj.likedCount);
const onClick = () => {
setLike(like + (click ? -1 : 1)); // status before click been used here
setClick(!click);
};
return (
<Like onClick={onClick} value={click}>{like}</Like>
)