首页 > 解决方案 > 如何将 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

标签: reactjsreact-hooks

解决方案


您从中获得的 setter 函数useState()需要传递参数,该参数将完全替换旧状态。所以你不能用它来更新标题,而不传递所有其他属性。

但是您可以从现有的状态对象派生一个新的状态对象,然后将整个对象传递给setQuestion()

setQuestion({
   ...question,
   title: "New title",
})

推荐阅读