反应推送状态提交

React push to state on submit

每次提交我的表单时,我都试图推送到我的反应状态,但在存储 2 个值后,状态开始被覆盖。函数代码:

  function addOrder(values: any) {
    let ordersArray: any[] = [];
    ordersArray.push({
      id: uuidv4(),
      client: clientsField?.label,
      catalog: catalogField?.label,
      product: productField.label,
      regularPrice: Number(productField.regularPrice),
      discountPrice: Number(productField.discountPrice),
      amount: values.amount,
      totalValue: values.amount * Number(productField.regularPrice),
    });
    setPedido(pedidosArray);
  }

更新:我可以提交表单,但我的状态仍然被覆盖

这样做不需要额外的数组:

  function adcionarPedido(values: any) {
    let pedidosArray = [...pedidos];
    pedidosArray.push({
      id: uuidv4(),
      cliente: clientesField?.label,
      catalogo: catalogoField?.label,
      produto: produtoField.label,
      valorRegular: Number(produtoField.valorRegular),
      valorOferta: Number(produtoField.valorOferta),
      quantidade: values.quantidade,
      valorBruto: values.quantidade * Number(produtoField.valorRegular),
    });
    setPedido(pedidosArray);
  }

t know why it doesn没用,但这是正确的方法怎么做:

  const [pedidosArray, setPedidosArray] = useState<any[]>();

  function adcionarPedido(values: any) {
    setPedidosArray((currentStateOfPediosArray) => 
     [...currentStateOfPediosArray, {
     id: uuidv4(),
     cliente: clientesField?.label,
     catalogo: catalogoField?.label,
     produto: produtoField.label,
     valorRegular: Number(produtoField.valorRegular),
     valorOferta: Number(produtoField.valorOferta),
     quantidade: values.quantidade,
     valorBruto: values.quantidade * Number(produtoField.valorRegular)
     })  
  };