简体   繁体   English

我正在尝试使用 React 中的 usestate 将元素添加到 object?

[英]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} &emsp; Value: {v} &emsp; &emsp; <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解释

  • The badStateObj is initialized with only id and name props badStateObj仅使用idname属性初始化
  • When user clicks the Add new prop button, a new prop may be added当用户点击Add new prop按钮时,可能会添加一个新道具
  • Separate buttons exist to update the value of each individual 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接受propNamepropVal作为参数并更新badStateObj中的适当道具。

暂无
暂无

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

相关问题 我正在尝试使用 react useState 挂钩来实现产品数量的增加和减少 - I am trying to implement product quantity increment and decrement using react useState hooks 我正在尝试使用 useState 在反应钩子中更新 object 内的 object - I'm trying to update object inside object in react hooks with useState 我正在尝试使用 React useState 挂钩更新 state? 创建读取和删除部分已完成,但我无法更新 - I am trying to update the state using the React useState hook?? The Create Read and Delete part has been done but iam not able to update 如何使用反应钩子 useState 从 API 向对象添加属性 - How to add property to an object from an API using react hooks useState 如何在 React 中使用 useState 在对象数组中添加 object? - How to add an object in an array of objects using useState in React? 我正在尝试向 js object 添加一个元素 - I am trying to add an element to a js object 为什么在 React 中尝试使用 useState 挂钩时出现“未定义”? - Why am I getting 'undefined' when trying to use the useState hook in React? UseState, UseEffect 不更新 reactjs 中的状态。 我正在尝试将随机数添加到状态 - UseState, UseEffect not updating state in reactjs. I am trying to add random number to state 我正在尝试将 object 添加到 object 中的数组末尾 - I am trying to add an object to the end of an array inside said object 尝试更新 object 内部的 object 中的数组。 反应,使用状态 - Trying to update an array in an object inside of an object. React, useState
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM