简体   繁体   中英

how do i add a key-value pair to an object in state of functional components

i've seen some stuff about computed property names for class components, is there a similar solution for functional components?

i have an initial state of {}.

const [choice, setChoice] = useState({})

as a button clicks, i'd like to add a new k:v to it dynamically.

onClick={()=>{ 
setChoice( props.choice[Key]=[Val] );
}

this doesn't seem to work...

and i'm hoping to add to the choice variable, like so: {"key":"val","key1":"val1",etc..)

i've also tried this:

class Choice {
    constructor(key, value){
      this.key = key,
      this.value = value
    }
  }

but not sure how to adjust the onClick for it.

the problem comes from your accessor for choice in the onClick function. The good syntax should be (because choice is accessible directly as a variable in your component)

onClick={()=>{ 
setChoice( { ...choice, key:val } ); 
}
  1. choice is state variable, so directly accessible by its name. No need to link to your component props with props.choice

  2. setChoice should take as an argument the original variable, plus the new key/value pair. Thus the destructuring of...choice and the added member variable key:value.

Edit: if you want your updates to be more sound with the React way, you should use the callback syntax. Finally you would have

setChoice(choice => { return {...choice, key:val}})

This preventing some noodling, coming from the asynchronous nature of state updates in React.

To add to the current state a new key value pair:

onClick={() => {
    setChoice( currentState => {
        return {...currentState, Key:Val}
        }
}}

The handler on set state has this overload that let's you use the previous state and add to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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