首页 > 解决方案 > 无法转换对象中值的数据类型

问题描述

我已经使用 mongoDB 作为数据库创建了 next.js 应用程序。

现在就像在我的代码中一样,当按钮被点击提交时,所有数据都将显示在表格中。我已经提取了我想要单独计算的所有数据,例如product_unitproduct_price。但是,因为该值已push作为productList文本输入。我无法计算它。

我尝试使用.parseInt转换,但它不起作用。

我应该怎么办?

我的代码:

const [jsxProductList, setJsxProductList] = useState(<tr></tr>);
const [productList, setProductList] = useState([]);

const onSubmitToDatabase = (data) => {
    console.log({ productList })
    fetch('/api/stock',
       {
           method: 'post',
           body: productList
       })
    }

const onSubmit = (data) => {

let j = 1
for (let i = 1; i <= productList.length; i++) {
  j++
}

var start_item_id = j
let p = { id: start_item_id, product_name: data.product_name, code: data.code, brand: 'Honda', model: 'CBR150', qty: data.qty, unitPrice: 100 }
productList.push(p)
console.log("productList", productList.length)
let newList = productList.map(p => {
  console.log("Update JSX", p)
  return (
    <tr>
      <td>{p.id}</td>
      <td>{p.product_name}</td>
      <td>{p.code}</td>
      <td>{p.brand}</td>
      <td>{p.model}</td>
      <td>{p.qty}</td>
      <td>{p.unitPrice}</td>
    </tr>
  )
})
setProductList(productList)
setJsxProductList(newList)

const product_code = []
const product_price = []
const product_unit = []
productList.map(p => {
  product_code.push(p.code)
  product_price.push(p.unitPrice)
  product_unit.push(p.qty)
})

product_unit.map(h => (
  h.parseInt
))

let total_unit, total_price = 0
for (let k = 0; k < product_unit.length; k++) {
  total_unit = total_unit + product_unit[k]
}}

for (let k = 0; k < product_price.length; k++) {
  total_unit = total_unit + product_unit[k]
}}

标签: reactjsmongodbnext.js

解决方案


尝试这个:

const new_product_unit = product_unit.map(h => parseInt(h));

// now use "new_product_unit" later in your code

推荐阅读