Javascript 如何创建键值对并将其推送到React中的状态?

Javascript 如何创建键值对并将其推送到React中的状态?,javascript,arrays,reactjs,react-native,Javascript,Arrays,Reactjs,React Native,我期望的输出如下所示 {'3afdrjke3j43kjkjf' : 3 , '8fsdfdsni3ni3dsfa' :2 } 我试着这样做,但没有成功 const [productQuantity, setProductQuantity] = useState([]); const handleQuantity = (e, id) => { setProductQuantity({id : e.target.value}) // this outputs {id :

我期望的输出如下所示

{'3afdrjke3j43kjkjf' : 3 , '8fsdfdsni3ni3dsfa' :2 }
我试着这样做,但没有成功

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

    const handleQuantity = (e, id) => {
      setProductQuantity({id : e.target.value}) // this outputs {id : "3"}
    }
每当我触发onchange事件时,id和传递给handleQuantity函数的数量。我想将键值对连接到状态

 <Form.Control onChange={(e) => handleQuantity(e, cartProduct._id)} as="select">
  {
   [...Array(cartProduct.quantity)].map((_, index) =>{
      return <option>{index + 1}</option>
    })
   }
 </Form.Control>
handleQuantity(e,cartProduct.\u id)}as=“select”>
{
[…数组(cartProduct.quantity)].map((\ux,index)=>{
返回{index+1}
})
}

提前感谢:)

要更新当前状态

setProductQuantity(状态=>({
状态
[id]:e.target.value
}))
这将使用新属性更新现有状态

如果这是您打算使用它的方式,您还应该将状态初始化为对象

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

要更新当前状态

setProductQuantity(状态=>({
状态
[id]:e.target.value
}))
这将使用新属性更新现有状态

如果这是您打算使用它的方式,您还应该将状态初始化为对象

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

您应该在您的状态中存储一个对象而不是数组,并在更改时将该对象与新对象合并

// 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,
  }));
};


您应该在您的状态中存储一个对象而不是数组,并在更改时将该对象与新对象合并

// 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,
  }));
};


在没有运行代码的情况下,我知道问题可能是什么。你在这么做吗

  • setProductQuantity({id:e.target.value})
您需要在数组中设置它

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

    • 如果没有运行您的代码,我就知道问题可能出在哪里了。你在这么做吗

      • setProductQuantity({id:e.target.value})
      您需要在数组中设置它

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

      那么您想在每次触发setProductQuantity时追加新条目吗?可以尝试setProductQuantity(productQuantity.concat([{id:e.target.value}]),谢谢!它与状态相关,但'id'应该像'34784asfdsaf'一样,而是返回{id:'2'},所以每次触发setProductQuantity时都要追加新条目?可以尝试setProductQuantity(productQuantity.concat([{id:e.target.value}]),谢谢!它与状态相关,但是'id'应该像'34784asfdsaf'一样,它返回{id:'2'}这将始终具有带有一个元素的数组。这将始终具有带有一个元素的数组。