[英]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?我已经看到一些关于 class 组件的计算属性名称的内容,功能组件是否有类似的解决方案?
i have an initial state of {}.我有 {} 的初始 state。
const [choice, setChoice] = useState({})
as a button clicks, i'd like to add a new k:v to it dynamically.当点击一个按钮时,我想动态地添加一个新的 k:v。
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..)我希望添加到选择变量中,像这样:{"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.但不确定如何为它调整 onClick。
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 function 中choice
的访问器。好的语法应该是(因为选择可以直接作为组件中的变量访问)
onClick={()=>{
setChoice( { ...choice, key:val } );
}
choice
is state variable, so directly accessible by its name. choice
是 state 变量,因此可以通过其名称直接访问。 No need to link to your component props with props.choice无需使用 props.choice 链接到您的组件道具
setChoice should take as an argument the original variable, plus the new key/value pair. setChoice 应该将原始变量加上新的键/值对作为参数。 Thus the destructuring of...choice and the added member variable key:value.于是解构了...choice 和添加的成员变量key:value。
Edit: if you want your updates to be more sound with the React way, you should use the callback syntax.编辑:如果你想让你的更新以 React 的方式更合理,你应该使用回调语法。 Finally you would have最后你会有
setChoice(choice => { return {...choice, key:val}})
This preventing some noodling, coming from the asynchronous nature of state updates in React.这防止了一些小问题,来自 React 中 state 更新的异步性质。
To add to the current state a new key value pair:向当前 state 添加一个新的键值对:
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.集合 state 上的处理程序具有此重载,让您可以使用之前的 state 并添加到其中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.