简体   繁体   English

如何制作键值对并将其推送到 React 中的状态?

[英]How to make a key value pairs and push it to state in React?

My desired output will look like this我想要的输出看起来像这样

{'3afdrjke3j43kjkjf' : 3 , '8fsdfdsni3ni3dsfa' :2 }

I tried like this but it didn't work我试过这样但没有用

const [productQuantity, setProductQuantity] = useState([]);

    const handleQuantity = (e, id) => {
      setProductQuantity({id : e.target.value}) // this outputs {id : "3"}
    }

Whenever i trigger onchange event the id and and the quantity passed on the the handleQuantity function.每当我触发 onchange 事件时,id 和传递给 handleQuantity 函数的数量。 Where i want to concat the key value pairs in to the state.我想将键值对连接到状态的地方。

 <Form.Control onChange={(e) => handleQuantity(e, cartProduct._id)} as="select">
  {
   [...Array(cartProduct.quantity)].map((_, index) =>{
      return <option>{index + 1}</option>
    })
   }
 </Form.Control>

Thanks in Advance :)提前致谢 :)

You should store an object not an array in your state and merge that object with the new one onChange您应该在您的状态中存储一个对象而不是数组,并将该对象与新的 onChange 合并

// start with an empty object
const [productQuantity, setProductQuantity] = useState({});

const handleQuantity = (e, id) => {
  // merge existing state with new [id]: value pair
  setProductQuantity((currentQuantity) => ({
    ...currentQuantity,
    // don't forget the brackets here
    [id]: e.target.value,
  }));
};

To update the current state, pass a function to the setter要更新当前状态, 请将函数传递给 setter

setProductQuantity(state => ({
  ...state,
  [ id ]: e.target.value
}))

This updates the existing state with a new property.这会使用新属性更新现有状态。

You should also initialise your state as an object if this is how you intend on using it如果这是您打算使用它的方式,您还应该将您的状态初始化为一个对象

const [ productQuantity, setProductQuantity ] = useState({})

With out running your code I have an idea what the problem might be.没有运行你的代码,我知道问题可能是什么。 You are doing this你在做这个

  • setProductQuantity({id : e.target.value}) setProductQuantity({id: e.target.value})

You need to set it in the array您需要将其设置在数组中

  • setProductQuantity([id] : e.target.value) setProductQuantity([id] : e.target.value)

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

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