如何像下面这样在 REACT table 上更新购物篮的数量?

How to update quantity on basket on REACT table like below?

我一直在尝试但没有任何运气,我在 Update 方法中的实现没有更新产品的状态。请协助我做错了什么。我正在使用带挂钩的功能组件。

function MyTable() {
  const initState = [
    { id: 1, name: "bread", quantitiy: 50, location: "cupboard" },
    { id: 2, name: "milk", quantitiy: 20, location: "fridge" },
    { id: 3, name: "water", quantitiy: 10, location: "fridge" }
  ];
  const [state, setState] = React.useState(initState);

  const handleUpdateQuantity = (productId: any, value: any) => {
    let newData = data;
    var index: number = newData.findIndex(
      (product: any) => product.id === productId
    )

    if (index !== -1) {
      newData[index].quantity = value
      setData(newData)
    } else {
      console.log("Product not existing on table data...")
    }
  }

  return (
    <table>
      <tr key={"header"}>
        {Object.keys(state[0]).map((key) => (
          <th>{key}</th>
        ))}
      </tr>
      {state.map((item) => (
        <tr key={item.id}>
          <td>{item.name}</td>
          <td>{item.location}</td>
            <TextField
                type="number"
                defaultValue={1}
                onChange={(event) =>
                    handleUpdateQuantity(item.id, event.target.value)
                }
            />
          <td>{item.quantitiy}</td>
        </tr>
      ))}
    </table>
  );
}

ReactDOM.render(<MyTable />, document.getElementById("target"));

您可以使用功能更新(因为新状态取决于之前的状态):

const handleUpdateQuantity = (productId: any, value: any) => {
    setData(prevData => prevData.map(el => {
        if(el.id === productId) {
            return {...el, quantity: value};
        }
        return el;
    }))
}

此外,quantitiys在初始状态中有错别字。

然后在 JSX 中,将值属性添加到文本字段:

<TextField
    type="number"
    defaultValue={1}
    value={item.quantity}
    onChange={(event) =>
        handleUpdateQuantity(item.id, event.target.value)
    }
/>