【问题标题】:How to make a key value pairs and push it to state in React?如何制作键值对并将其推送到 React 中?
【发布时间】:2021-01-12 09:08:32
【问题描述】:

我想要的输出是这样的

{'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>

在此先感谢 :)

【问题讨论】:

  • 所以您想在每次触发 setProductQuantity 时追加新条目?可以试试 setProductQuantity(productQuantity.concat([{id : e.target.value}]))
  • 谢谢!它正在连接到状态,但“id”应该是这样的“34784asfdsaf”而不是它返回 {id :'2'}

标签: javascript arrays reactjs react-native


【解决方案1】:

您应该在您的状态中存储一个对象而不是数组,并将该对象与新的 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,
  }));
};

【讨论】:

    【解决方案2】:

    要更新当前状态,pass a function to the setter

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

    这会使用新属性更新现有状态。

    如果您打算使用它,您还应该将您的状态初始化为一个对象

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

    【讨论】:

      【解决方案3】:

      如果不运行您的代码,我就知道问题可能出在哪里。你正在这样做

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

      需要在数组中设置

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

      【讨论】:

      • 这总是有一个元素的数组。
      猜你喜欢
      • 2020-06-28
      • 1970-01-01
      • 1970-01-01
      • 2020-12-26
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      相关资源
      最近更新 更多