reactjs - 如何将 useState 与 {} 一起使用?
问题描述
鉴于这种..
const [question, setQuestion] = useState({})
并且question
可以包含标题和描述。
IE
{
title: 'How to use useState with {}?',
decription: 'given this..`const [question, setQuestion] = useState({})`and `question` can contain a title and a description. I.E. { title: 'How to use useState with {}?', decription: '' }How can the title and description be set independently with `setQuestion`?'
}
标题和描述如何独立设置setQuestion
?
解决方案
您从中获得的 setter 函数useState()
需要传递参数,该参数将完全替换旧状态。所以你不能用它来更新标题,而不传递所有其他属性。
但是您可以从现有的状态对象派生一个新的状态对象,然后将整个对象传递给setQuestion()
setQuestion({
...question,
title: "New title",
})
推荐阅读
- python - 初始化 Django 对象的最优雅或 Pythonic 方式是什么?
- android - Android Jetpack Compose:未解决的参考:Intent
- python - 如何计算实际总字段的总值并将此值存储在odoo模型中的另一个字段中?
- java - persistence.xml 配置到纯 Java JDO 配置
- spring - Hibernate/JPA - 是否可以有一个具有父母 ID + 另一个字段的孩子?
- python - 用于 Excel 的 Python 自动化
- python - 为什么我无法在下拉列表中选择项目?
- git - 无法更新 git 以使用访问令牌而不是密码
- python-3.x - 如何在加载 Tkinter 窗口后让 tts (pyttsx3) 说话
- mysql - 将值从客户表访问到房间类型表