useState 更新对象内多个变量的实例变量
const [emoji, setEmoji] = useState({
like: 0,
love: 0,
laugh: 0,
sad: 0,
wow: 0,
angry: 0,
})
const emojiCount = () => {
isReacted
?
setEmoji(emoji => ({...emoji, laugh: emoji.laugh+1}))
:
setEmoji(emoji => ({...emoji, laugh: emoji.laugh-1}))
setIsReacted(!isReacted)
}
- isReacted 只是一个布尔状态!
我想要实现的是使用函数“emojiCount”处理整个状态,我想知道我是否能够将“笑”作为动态变量传递,其中可以是“爱”或“喜欢”等。
const [emoji, setEmoji] = useState({
like: 0,
love: 0,
laugh: 0,
sad: 0,
wow: 0,
angry: 0,
})
const emojiCount = () => {
isReacted
?
setEmoji(emoji => ({...emoji, laugh: emoji.laugh+1}))
:
setEmoji(emoji => ({...emoji, laugh: emoji.laugh-1}))
setIsReacted(!isReacted)
}
- isReacted is just a boolean state!
What I am trying to implement is to handle the whole state with the function "emojiCount", I want to know if I am capable of passing "laugh" as a dynamic variable where it can be "love" or "like" etc..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你想要做的是动态传递对象键,你可以这样做:
因此,如果你调用像
emojiCount("laugh")
这样的函数,它将更新笑键,增加笑声值减 1。这是一个带有更新表情符号的动态按钮的沙箱:
https://codesandbox.io/s/adoring-benz -2zeyzh?file=/src/App.js
I think what you want to do is pass the object key dynamically, you can do that like this:
So if you call the function like
emojiCount("laugh")
it will update the laugh key incrementing the laugh value by 1.Here's a sandbox with dynamic buttons that update the emoji:
https://codesandbox.io/s/adoring-benz-2zeyzh?file=/src/App.js