简体   繁体   English

推送数组长度保持不变

[英]Push array length remains constant

I am new in react and I want to push values when click Ok of Modal.我是反应新手,我想在单击模态的确定时推送值。 For example, if i want to add egg drop, and then add Chicken burrito, both of these are added in array in Navbar state Total_Item.例如,如果我想添加鸡蛋滴,然后添加鸡肉卷饼,这两个都添加到导航栏 state Total_Item 的数组中。

The problem is that the items are added, but the length of array remain 2. It seems that array size remain constant, and one array is saved in another array.问题是添加了项目,但数组的长度保持为2。似乎数组大小保持不变,一个数组保存在另一个数组中。 I need to fix the length size, so later i can run logic to keep unique values.我需要修复长度大小,以便稍后我可以运行逻辑来保持唯一值。 Please see Menu component and check Listval() function.请参阅菜单组件并检查 Listval() function。

I need to correct the push array logic.Please see the sandbox: https://codesandbox.io/s/mutable-water-8779d我需要更正推送数组逻辑。请查看沙箱: https://codesandbox.io/s/mutable-water-8779d

thanks谢谢

App Component应用组件


import React, {Component} from "react";
import Navbar from "./components/Navbar";
import "./styles.css";

class App extends Component {
render (){
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Navbar/>
    </div>
  );


}
   
}

export default App;

Navbar Component导航栏组件

import React, {Component} from "react";
import Menu from "./Menu";

class Navbar extends Component {
  state={
Category:[
  {
    id:1,
    FoodType: "Chinese",
    Menu:["Egg Drop", "Chicken Fried", "Beef Fried"],
    Price:[2,8,10]
    },
    
    {
      id:2,
      FoodType: "Mexican",
      Menu:["Veg Burrito", "Chicken Burrito", "Beef Burrito"],
      Price:[7,8,10]
      }

],

One_Item:[
{
  listvalue:null,
  Select_Item:null,
  Select_Price:null,
  Select_Quantity:null,
  Select_Item_TotalPrice:null

}

],

Cart_Item:[

  {
Total_Item:[]

  }
]



  };




  render() {
    return (

   <Menu
  //  len={this.state.length}
  //  FoodTypes_list = {this.state.map(e => e.FoodType)}
  //  MenuList_list={this.state.map(e => e.Menu)}


Objs_Type={this.state.Category}




  //  FoodTypes={this.state.Type1.FoodType}
  //  MenuList={this.state.Type1.Menu}
 
   />

    );


  }
}
export default Navbar;

Menu Component菜单组件

import React, { Component } from "react";
import { Modal } from "react-bootstrap";
import NumericInput from "react-numeric-input";

class Menu extends Component {
  state = {
    addModalShow: false,
    copied: false
  };

  ModalShow = () => {
    this.setState({ addModalShow: true });
  };

  async ModalText(e) {
    await this.setState({ listvalue: e.target.innerHTML });

    //  console.log(this.state.listvalue);
  }

  ModalClose = () => {
    this.setState({ addModalShow: false });
  };

  async Listval() {
    let ll = "$" + this.state.listvalue.replace(/[^0-9]/g, "");

    let ll2 = this.state.listvalue.replace(/\d+/g, "");
    let ll3 = ll2.replace(/\$/g, "");

    let ll4 = ll.replace(/\$/g, "");
    let ll5 = this.state.Select_Quantity;
    let ll6 = parseFloat(ll4) * ll5;

    let ll7 = [this.state.Total_Item];
    ll7.push(ll3);

    // this.state.ll7.map((e,idx) => {
    //   key={idx}
    // };

    // for(var i=0;i<ll7.length;i++){
    //   // push the component to elements!
    //  return ll7[key=i]
    // };

    // ll7.filter((item,index)=>{
    //   return ll7.indexOf(item)===index
    // });

    // let ll2='$'+ll.replace(/[^0-9]/g,'');
    await this.setState({ Select_Price: ll });
    await this.setState({ Select_Item: ll3 });
    await this.setState({ Select_Item_TotalPrice: ll6 });

    await this.setState({ Total_Item: ll7 });

    console.log(this.state.Total_Item);
  }

  stylesList = {
    display: "inline-block",
    background: "#C8C8C8",
    width: "500px",
    height: "50px"
  };

  onhover = e => {
    e.target.style.background = "red";
  };

  offhover = e => {
    e.target.style.background = "#C8C8C8 ";
  };

  render() {
    return <div className="container-fluid">{this.Mapping_Type()}</div>;
  }

  Mapping_Type() {
    let result_type = this.props.Objs_Type.map(a => a.FoodType);
    let result_menu = this.props.Objs_Type.map(a => a.Menu);
    let result_price = this.props.Objs_Type.map(a => a.Price);

    let newFoodtype = [];
    let newMenu = [];
    let FoodType_Menu = [];
    let Price_new = [];
    for (let i = 0; i < result_type.length; i++) {
      let temp1 = <h1> Menu {result_type[i]}</h1>;
      let temp2 = result_menu[i].map((item, idx) => (
        <div style={this.stylesList}>
          <ul style={{ padding: 0 }}>
            {/* <CopyToClipboard> */}
            <li
              id={idx}
              style={{ listStyleType: "none" }}
              key={item.id}
              className={"listitems"}
              onMouseOver={this.onhover}
              onMouseOut={this.offhover}
              onClick={e => {
                this.ModalShow();
                this.ModalText(e);
              }}
            >
              {" "}
              {item} {result_price[i][idx]}{" "}
            </li>
            {/* </CopyToClipboard> */}

            <Modal
              style={{ opacity: 1 }}
              size="md"
              aria-labelledby="contained-modal-title-vcenter"
              show={this.state.addModalShow}
              onHide={this.ModalClose}
            >
              <Modal.Header closeButton>
                <Modal.Title id="contained-modal-title-vcenter">
                  Large Modal
                </Modal.Title>
              </Modal.Header>
              <Modal.Body>
                <div className="container">
                  {this.state.listvalue}
                  <br />
                  <NumericInput
                    min={1}
                    max={1000}
                    value={this.state.Select_Quantity}
                    onChange={value =>
                      this.setState({ Select_Quantity: value })
                    }
                    style={{ float: "right", width: "500px", padding: "10px" }}
                  />

                  <br />

                  <button
                    class="btn btn-primary btn-sm pull-right"
                    onClick={() => {
                      this.Listval();
                    }}
                  >
                    OK
                  </button>
                </div>
              </Modal.Body>
            </Modal>
          </ul>
        </div>
      ));

      FoodType_Menu.push(temp1, temp2);
    }
    return FoodType_Menu;
  }
}

export default Menu;


Isn't Total_Item?不是Total_Item? an array itself?数组本身?

when you do this:当你这样做时:

let ll7 = [this.state.Total_Item];

you are creating an array ( [] ) that contains the Total_Item array.您正在创建一个包含Total_Item数组的数组 ( [] )。 And then, with this line:然后,用这一行:

ll7.push(ll3);

You push ll3 into your array.您将ll3推入您的阵列。 So your array now contains the Total_Item array and ll3 .因此,您的数组现在包含Total_Item数组和ll3

If Total_Item is an array, it would be:如果Total_Item是一个数组,它将是:

let ll7 = this.state.Total_Item || [];
ll7.push(ll3);

Or if you want an independent array, you can use the ... spread operator:或者如果你想要一个独立的数组,你可以使用...扩展运算符:

let ll7 = [...(this.state.Total_Item || [])];
ll7.push(ll3);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM