用 prop 改变 Usestate 对象

change Usestate Object with prop

我正在尝试更改 selectedItems 对象中项目的值,但是 changeSelectedItems 函数总是将变量名设置为 type 而不是 [=16= 的值] 'type'。 我如何使用类型 属性 作为值的名称?

const [selectedItems, SetselectedItems] = useState({
  shirt:'none',
  pants:'none',
  hat:'none',
})

const changeSelectedItems = (name,type) =>{
  SetselectedItems({type:name})
}

<div onClick={() =>changeSelectedItems('blue shirt','shirt')}> blue shirt </div>
<div onClick={() =>changeSelectedItems('jeans','pants')}> jeans </div>
<div onClick={() =>changeSelectedItems('tophat','hat')}> tophat </div>

应该是

  const [selectedItems, SetselectedItems] = useState({
    shirt:'none',
    pants:'none',
    hat:'none',
  })

  const changeSelectedItems = (name,type) =>{
    SetselectedItems(selected => ({...selected, [type]:name}))
  }

<div onClick={() =>changeSelectedItems('blue shirt','shirt')}> blue shirt </div>
<div onClick={() =>changeSelectedItems('jeans','pants')}> jeans </div>
<div onClick={() =>changeSelectedItems('tophat','hat')}> tophat </div>

如果您想更改特定键的状态,请这样做

SetselectedItems(oldState => ({...oldState, [type]:name}))

扩展运算符... 获取所有对象,但没有输入值的特定键

就去吧:

 const changeSelectedItems = (name,type) =>{
    SetselectedItems({...selectedItems, [type]: name })
  }

这里有一些关于 spread syntax I've used and you can read more about computed properties in this article 的信息。