【问题标题】:How to add objects to an array in React and redux如何在 React 和 redux 中将对象添加到数组中
【发布时间】:2020-11-14 18:56:25
【问题描述】:

我正在处理一个接受客户订单的表单,并且我正在使用 React Redux 来管理我的状态。有一个名为 items 的对象数组,我将订单的项目添加到其中。每个项目都是 4 个属性(名称、数量、价格、说明)的对象。以下是我处理表单的方式:

for (let i = 0; i < numOfItems; i++) {
        rows.push(
            <div key={i} className="add-items-form">
                <div className="items-header-container">
                    <h3 className="items-form-header">ITEM #{i + 1}</h3>
                    <Button onClick={() => removeItem(i)}>Remove Item</Button>
                </div>
                <div className="row">
                    <FormGroup className="col-md-6">
                        <Label >Item Name</Label>
                        <Input type="text" name="name" onChange={setFormValue} value={form.items.name} />
                    </FormGroup>
                    <FormGroup className="col-md-6">
                        <Label >QTY</Label>
                        <Input type="number" name="quantity" onChange={setFormValue} value={form.items.quantity} />
                    </FormGroup>
                </div>
                <div className="row">
                    <FormGroup className="col-md-6">
                        <Label >Price</Label>
                        <Input type="number" name="price" onChange={setFormValue} value={form.items.price} />
                    </FormGroup>
                    <FormGroup className="col-md-6">
                        <Label >Special Instructions</Label>
                        <Input type="text" name="special_instructions" onChange={setFormValue} value={form.items.special_instructions} />
                    </FormGroup>
                </div>
            </div>
        )
    };

这是接受输入的 redux 操作:

export function setFormValue(field) {
    console.log("FIELD", field.target.value)
    return function (dispatch) {
        dispatch({ type: types.SET_FORM_VALUE, payload: field })
    };
}

这是我的减速器功能,我正在处理表单中的部分项目:

 if (action.payload.target.name === "items") {
                let cloneditems = [...state.form.items];
                cloneditems.push(action.payload.target.value);
                return {
                    ...state,
                    form: {
                        ...state.form,
                        items: cloneditems
                    }
                };
            }

我计划做的是添加一个项目对象并将其推送到项目数组中,每次我在表单中添加一个项目及其详细信息时。然而,它将它们添加到 items 数组之外,而不是作为对象添加到其中。任何人都可以帮助我完成这部分,因为它消耗大量时间而我无法完成?如果你想看看,这是我的项目的链接:

https://codesandbox.io/s/hopeful-williamson-nvqx9?file=/src/redux/reducer.js

这是我打算得到的一个例子:

form : {
     user :[{
          name: "",
          quantity:"",
          price:"",
          instructions:""
     }]
}

此外,这是我的 reducer 初始状态:

const initialState = {
    form: {
        pickup_address: {},
        delivery_address: {},
        items: [{
            index: 0,
            name: "",
            quantity: 0,
            price: 0,
            special_instructions: ""
        }]
    },
    numOfItems: 0,
};

有什么帮助吗?!

【问题讨论】:

  • 我会投赞成票,因为这很难解决,也分享 for 循环......我会删除你之前的问题以避免被投反对票。
  • 也分享reducer的初始状态。
  • @BARNOWL 谢谢一百万兄弟。如果您有时间,请您再次查看该表格,因为您的第一个修复程序无法使用它。
  • 对不起。其他人可能会提供帮助,因为这不是一个简单的解决方法。你的代码有问题。如果我是你,我肯定会研究像这样的反应文档reactjs.org/docs/lists-and-keys.html :) 一切顺利。
  • @BARNOWL 好的。还是谢谢。

标签: javascript reactjs redux


【解决方案1】:

https://codesandbox.io/s/cocky-haze-5p346?file=/src/forms/itemForm.js

立即尝试

项目详情

for (let i = 0; i < numOfItems; i++) {
    rows.push(
      <ItemForm
        index={i}
        removeItem={removeItem}
        setItemName={setItemName}
        setQuantity={setQuantity}
        setPrice={setPrice}
        setInstructions={setInstructions}
        itemName={name}
        qty={quantity}
        price={price}
        special_instructions={special_instructions}
      />
      // <div key={i} className="add-items-form">
      //   <div className="items-header-container">
      //     <h3 className="items-form-header">ITEM #{i + 1}</h3>
      //     <Button onClick={() => removeItem(i)}>Remove Item</Button>
      //   </div>
      //   <div className="row">
      //     <FormGroup className="col-md-6">
      //       <Label>Item Name</Label>
      //       <Input
      //         type="text"
      //         name="name"
      //         onChange={e => setItemName(e.target.value)}
      //         value={itemName}
      //       />
      //     </FormGroup>
      //     <FormGroup className="col-md-6">
      //       <Label>QTY</Label>
      //       <Input
      //         type="text"
      //         name="quantity"
      //         onChange={e => setQuantity(e.target.value)}
      //         value={qty}
      //       />
      //     </FormGroup>
      //   </div>
      //   <div className="row">
      //     <FormGroup className="col-md-6">
      //       <Label>Price</Label>
      //       <Input
      //         type="text"
      //         name="price"
      //         onChange={e => setPrice(e.target.value)}
      //         value={price}
      //       />
      //     </FormGroup>
      //     <FormGroup className="col-md-6">
      //       <Label>Special Instructions</Label>
      //       <Input
      //         type="text"
      //         name="special_instructions"
      //         onChange={e => setInstructions(e.target.value)}
      //         value={instructions}
      //       />
      //     </FormGroup>
      //   </div>
      // </div>
    );
  }

itemForm.js

import React, { useState } from "react";
import { Button, FormGroup, Input, Label } from "reactstrap";
function ItemForm(props) {
  console.log("dssd", props.price);
  return (
    <div key={props.index} className="add-items-form">
      <div className="items-header-container">
        <h3 className="items-form-header">ITEM #{props.index + 1}</h3>
        <Button onClick={() => props.removeItem(props.index)}>
          Remove Item
        </Button>
      </div>
      <div className="row">
        <FormGroup className="col-md-6">
          <Label>Item Name</Label>
          <Input
            type="text"
            name="name"
            onChange={e => props.setItemName(e.target.value)}
            value={props.name}
          />
        </FormGroup>
        <FormGroup className="col-md-6">
          <Label>QTY</Label>
          <Input
            type="text"
            name="quantity"
            onChange={e => props.setQuantity(e.target.value)}
            value={props.quantity}
          />
        </FormGroup>
      </div>
      <div className="row">
        <FormGroup className="col-md-6">
          <Label>Price</Label>
          <Input
            type="text"
            name="price"
            onChange={e => props.setPrice(e.target.value)}
            value={props.price}
          />
        </FormGroup>
        <FormGroup className="col-md-6">
          <Label>Special Instructions</Label>
          <Input
            type="text"
            name="special_instructions"
            onChange={e => props.setInstructions(e.target.value)}
            value={props.instructions}
          />
        </FormGroup>
      </div>
    </div>
  );
}

export default ItemForm;

【讨论】:

    【解决方案2】:

    如果发布 CodeSandbox 链接就好了,

    我刚刚发布了将对象添加到数组的简单方法,也许有帮助。

    var myArray = ["Red", "Green", "Blue"];
    myArray.push("Yellow");
    
    var myObject = {id: 1, name: "Amoos", class: 10}; 
    
    myArray.push(myObject);
    
    console.log(myArray)
    猜你喜欢
    • 1970-01-01
    • 2018-08-22
    • 2020-10-08
    • 2019-10-02
    • 1970-01-01
    • 2017-07-12
    • 2021-12-23
    • 2020-08-24
    • 1970-01-01
    相关资源
    最近更新 更多