[英]I am trying to add elements to object using usestate in React?
I am trying to add a new fields in the useState hook我正在尝试在 useState 挂钩中添加新字段
// prevstate
let [currentdata, setcurrentdata] = useState({
id:'',
name:''
})
I try to add new fields in the object like that我尝试像这样在 object 中添加新字段
setcurrentdata(currentdata => ({
...currentdata,
q: quantity,
}))
but it did not add new fields但它没有添加新字段
The code snippet below may be one possible solution to achieve the desired objective.下面的代码片段可能是实现预期目标的一种可能解决方案。
NOTE: I personally dislike the idea of using useState in conjunction with such objects & prefer multiple simpler useState on each variable instead.注意:我个人不喜欢将 useState 与此类对象结合使用的想法,而是更喜欢在每个变量上使用多个更简单的 useState。
Code Snippet代码片段
const {useState} = React; const MyFunction = () => { const [badStateObj, setBadStateObj] = useState({ id: '', name: '' }); const clickHandler = (propName) => setBadStateObj(prev => ({...prev, [propName]: prev[propName] || '' })); const updateHandler = (propName, propVal) => setBadStateObj(prev => ({...prev, [propName]: propVal })); return ( <div> {Object.entries(badStateObj).map(([k,v]) => ( <div> Key: {k}   Value: {v}     <button onClick={() => updateHandler(k, prompt( `Enter new value for ${k}` ))} > Update {k} </button> </div> ))} <button onClick={() => clickHandler(prompt('Enter prop name'))} > Add new prop </button> </div> ); }; ReactDOM.render( <div> <h4>Demo showing the useState that I personally dislike</h4> <MyFunction /> </div>, document.getElementById("react") );
<div id="react"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
Explanation解释
badStateObj
is initialized with only id
and name
props badStateObj
仅使用id
和name
属性初始化Add new prop
button, a new prop may be addedAdd new prop
按钮时,可能会添加一个新道具clickHandler
adds the new prop entered by user with ''
value. clickHandler
将用户输入的新属性添加为''
值。updateHandler
accepts propName
and propVal
as parameters and updates the appropriate props within the badStateObj
. updateHandler
接受propName
和propVal
作为参数并更新badStateObj
中的适当道具。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.