I am trying to add a new fields in the useState hook
// prevstate
let [currentdata, setcurrentdata] = useState({
id:'',
name:''
})
I try to add new fields in the object like that
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.
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 Add new prop
button, a new prop may be addedclickHandler
adds the new prop entered by user with ''
value. updateHandler
accepts propName
and propVal
as parameters and updates the appropriate props within the badStateObj
.
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.