简体   繁体   English

用 prop 改变 Usestate Object

[英]change Usestate Object with prop

I am trying to change the value of items in the selectedItems Object, but the changeSelectedItems function always sets the name of the variable to type instead of the value of the property 'type'.我试图更改selectedItems Object 中项目的值,但changeSelectedItems function 始终将变量的名称设置为 type 而不是属性“type”的值。 How do i use the type property as the name for the value?我如何使用类型属性作为值的名称?

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>

it should be它应该是

  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>

if you want to change the state of a specific key do it like this如果你想改变特定键的 state 这样做

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

the spread operator ... get all object without what specific key you put the value传播运算符...得到所有 object 没有你输入值的具体键

Just go:只是 go:

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

Here's some info about the spread syntax I've used and you can read more about computed properties in this article .这里有一些关于我使用的扩展语法的信息,您可以在本文中阅读更多关于计算属性的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM