根据在React中输入的输入总数更新输入最大值

时间:2017-09-19 13:35:36

标签: javascript arrays json if-statement state

我正在创建一个应用程序,我有一个从JSON文件解析的数组,它为每个“捆绑”产品提供了最大数量的外围设备。我基本上需要实现的是,一旦达到最大输入数量,输入的最大值就会更新,这样用户就无法再向包中添加任何产品。有谁知道在React / Javascript中这样做的方法。

我的代码如下

import React, { Component } from "react";
import "./App.css";
import productdata from "./catalog.json";
import productSort from "./OrderDetails";


class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      BundleVal: "",
      ProductCounter: [],
      PeripheralCounter: 0,
      InstallationCounter: [],
      forenameVal: "",
      surnnameVal: "",
      addressoneVal: "",
      addresstwoVal: "",
      cityVal: "",
      countyVal: "",
      postcodeVal: "",
      phoneVal: "",
      emailVal: "",
      dobVal: ""
    };
  }

      forenameUpdate = (val) => {
        this.setState({
          forenameVal: val
        })
      };

      surnameUpdate = (val) => {
        this.setState({
          surnameVal: val
        })
      };
      addressoneUpdate = (val) => {
        this.setState({
          addressoneVal: val
        })
      };

      addresstwoUpdate = (val) => {
        this.setState({
          addresstwoVal: val
        })
      };

      cityUpdate = (val) => {
        this.setState({
          cityVal: val
        })
      };

      countyUpdate = (val) => {
        this.setState({
          countyVal: val
        })
      };
      postcodeUpdate = (val) => {
        this.setState({
          postcodeVal: val
        })
      };
      phoneUpdate = (val) => {
        this.setState({
          phoneVal: val
        })
      };

      emailUpdate = (val) => {
        this.setState({
          emailVal: val
        })
      };

      dobUpdate = (val) => {
        this.setState({
          dobVal: val
        })
      };

      installationUpdate = (val) => {
        this.setState({
          installVal: val
        })
      };

      updateBundle = val => {
        this.setState({
          BundleVal: val
        });
      };

  updateQuantity = e => {
    var pCounter = this.state.ProductCounter;
    var el = parseInt(e.target.id.split("_")[1], 10);
    pCounter[el] = parseInt(e.target.value, 10);
    this.setState({ ProductCounter: pCounter });
  };


  render() {

    let bname = null;
    let maxperipherals = null;
    if (this.state.BundleVal === "1") {
      bname = productdata.data.bundles[0].name;
      maxperipherals = productdata.data.bundles[0].maximumPeripherals;
    } else if (this.state.BundleVal === "2") {
      bname = productdata.data.bundles[1].name;
      maxperipherals = productdata.data.bundles[1].maximumPeripherals;
    } else if (this.state.BundleVal === "3") {
      bname = productdata.data.bundles[2].name;
      maxperipherals = productdata.data.bundles[2].maximumPeripherals;
    } else if (this.state.BundleVal === "4") {
      bname = productdata.data.bundles[3].name;
      maxperipherals = productdata.data.bundles[3].maximumPeripherals;
    } else {
      bname = null;
      maxperipherals = "N/A";
    }



    const BundleProducts = [].concat(productSort).map((item, i) =>
      <div key={item.id}>
        {item.id} <br />
        {item.name} <br />
        {item.description} <br />
        Installation: £{item.price.installation} <br />
        Monthly: £{item.price.recurring} <br />
        <input
          type="number"
          onChange={this.updateQuantity}
          value={this.state.ProductCounter[item.id] || 0}
          id={"product_" + item.id}
        />
        <br />
        {this.state.ProductCounter[item.id] || 0}<br />
        <hr />
      </div>
    );

    if (this.state.PeripheralCounter >= maxperipherals) {
        alert ("You Cannot Add any more Peripherals");
        this.state.ProductCounter;  
    } 


    var installationTotal = 0;  // Variable to hold your total  
      for(var t = 0, instalen = BundleProducts.length; t < instalen; t++) {
        installationTotal += BundleProducts[t].props.children[19] * BundleProducts[t].props.children[10];  
    }
    var installTotal = parseFloat(installationTotal, 10).toFixed(2)

    var recurringTotal = 0;  // Variable to hold your total 
      for(var r = 0, recurlen = BundleProducts.length; r < recurlen; r++) {
        recurringTotal += BundleProducts[r].props.children[19] * BundleProducts[r].props.children[14];  
    }
    var monthlyTotal = parseFloat(recurringTotal, 10).toFixed(2)



    this.state.PeripheralCounter = this.state.ProductCounter
      .filter(function(qty, pid) {
        pid = String(pid);
        for (var i = 0; i < productSort.length; i++) {
          var p = productSort[i];
          if (p.isPeripheral === true && p.id === pid) {
            return true;
          }
        }
        return false;
      })
      .reduce(function(count, carry) {
        return count + carry;
      }, 0);



    return (
      <div>
        <h2>Order</h2>
        Chosen Bundle: {bname}
        <br />
        Number of Peripherals: {this.state.PeripheralCounter}
        <br />
        Maximum Number of Peripherals: {maxperipherals}
        <br />
        Peripherals Installation Cost Total: £{installTotal}
        <br />
        Peripherals Monthly Cost Total: £{monthlyTotal}
        <br />
        Customer Name: {this.state.forenameVal} {this.state.surnameVal}
        <br />
        Customer Address: 
            {this.state.addressoneVal} 
            {this.state.addresstwoVal} 
            {this.state.cityVal} 
            {this.state.countyVal} 
            {this.state.postcodeVal} 
        <br />
        Customer Phone: {this.state.phoneVal} 
        <br />
        Customer Email: {this.state.emailVal} 
        <br />
        Customer Date of Birth: {this.state.dobVal} 
        <Bundle updateBundle={this.updateBundle} />
        <h3>Products</h3>
        {BundleProducts}
        <br/>
        <Customer 
        forenameUpdate={this.forenameUpdate} 
        surnameUpdate={this.surnameUpdate} 
        addressoneUpdate={this.addressoneUpdate} 
        addresstwoUpdate={this.addresstwoUpdate} 
        cityUpdate={this.cityUpdate}
        countyUpdate={this.countyUpdate}
        postcodeUpdate={this.postcodeUpdate}
        phoneUpdate={this.phoneUpdate}
        emailUpdate={this.emailUpdate}
        dobUpdate={this.dobUpdate}
        />
      </div>
    );
  }
}


class Bundle extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      BundleVal: ""
    };
  }

  updatebundle = e => {
    this.props.updateBundle(e.target.value);
    this.setState({ BundleVal: e.target.value });
  };

  render() {
    return (
      <div>
        <h4>Bundle</h4>
        <input
          type="radio"
          value="1"
          onChange={this.updatebundle}
          checked={this.state.BundleVal === "1"}
        />
        Indoor Camera RAPID
        <input
          type="radio"
          value="2"
          onChange={this.updatebundle}
          checked={this.state.BundleVal === "2"}
        />
        Alarm Only RAPID
        <input
          type="radio"
          value="3"
          onChange={this.updatebundle}
          checked={this.state.BundleVal === "3"}
        />
        Outdoor Camera RAPID
        <input
          type="radio"
          value="4"
          onChange={this.updatebundle}
          checked={this.state.BundleVal === "4"}
        />
        Build Your Own Bundle
      </div>
    );
  }
}



class Customer extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      forenameVal: "",
      surnnameVal: "",
      addressoneVal: "",
      addresstwoVal: "",
      cityVal: "",
      countyVal: "",
      postcodeVal: "",
      phoneVal: "",
      emailVal: "",
      dobVal: ""
    }
  }

  updateForename = (e) => {
    this.props.forenameUpdate(e.target.value);
    this.setState({forenameVal: e.target.value});
  };

  updateSurname = (e) => {
    this.props.surnameUpdate(e.target.value);
    this.setState({surnameVal: e.target.value});
  };

  updateAddressone = (e) => {
    this.props.addressoneUpdate(e.target.value);
    this.setState({addressoneVal: e.target.value});
  };

  updateAddresstwo = (e) => {
    this.props.addresstwoUpdate(e.target.value);
    this.setState({addresstwoVal: e.target.value});
  };

  updateCity = (e) => {
    this.props.cityUpdate(e.target.value);
    this.setState({cityVal: e.target.value});
  };

  updateCounty = (e) => {
    this.props.countyUpdate(e.target.value);
    this.setState({countyVal: e.target.value});
  };

  updatePostcode = (e) => {
    this.props.postcodeUpdate(e.target.value);
    this.setState({postcodeVal: e.target.value});
  };  

  updatePhone = (e) => {
    this.props.phoneUpdate(e.target.value);
    this.setState({phoneVal: e.target.value});
  };

  updateEmail = (e) => {
    this.props.emailUpdate(e.target.value);
    this.setState({emailVal: e.target.value});
  };

  updateDob = (e) => {
    this.props.dobUpdate(e.target.value);
    this.setState({dobVal: e.target.value});
  };

  render() {
    return (
      <div>
        <h4>Customer</h4>
        First Name: <input
          type="text"
          placeholder="type here"
          onChange={this.updateForename}
          value={this.state.forenameVal}
        />
        <br />
        Last Name: <input
          type="text"
          placeholder="type here"
          onChange={this.updateSurname}
          value={this.state.surnameVal}
        />
        <br />
        Address Line One: <input
          type="text"
          placeholder="type here"
          onChange={this.updateAddressone}
          value={this.state.addressoneVal}
        />
        <br />
        Address Line Two: <input
          type="text"
          placeholder="type here"
          onChange={this.updateAddresstwo}
          value={this.state.addresstwoVal}
        />
        <br />
        Town/City: <input
          type="text"
          placeholder="type here"
          onChange={this.updateCity}
          value={this.state.cityVal}
        />
        <br />
        County: <input
          type="text"
          placeholder="type here"
          onChange={this.updateCounty}
          value={this.state.countyVal}
        />
        <br />
        Postcode: <input
          type="text"
          placeholder="type here"
          onChange={this.updatePostcode}
          value={this.state.cpostcodeVal}
        />
        <br />
        Phone: <input
          type="text"
          placeholder="type here"
          onChange={this.updatePhone}
          value={this.state.phoneVal}
        />
        <br />
        Email: <input
          type="text"
          placeholder="type here"
          onChange={this.updateEmail}
          value={this.state.emailVal}
        />
        <br />
        Date of Birth: <input
          type="date"
          placeholder="type here"
          onChange={this.updateDob}
          value={this.state.dobVal}
        />
      </div>
    )
  }
}


export default App;

我正在解析的JSON文件的示例如下

{
    "timestamp": 1502121471,
    "data": {
        "adverts": [],
        "bundles": [{
            "id": "1",
            "name": "Bundle 1",
            "description": "Bundle 1 Description",
            "maximumPeripherals": 32,
            "available": true,
            "count": 0,  
            "price": {
                "installation": "99.99",
                "recurring": "23.99"
            },
            "image": {
                "file": "bundle-one.png",
            },
            "products": ["1", "2", "3"]
        }, {
            "id": "2",
            "name": "Bundle 2",
            "description": "Bundle 2 Description",
            "maximumPeripherals": 32,
            "available": true,
            "count": 0,  
            "price": {
                "installation": "99.99",
                "recurring": "23.99"
            },
            "image": {
                "file": "bundle-two.png",

            },
            "products": ["1", "2", "2", "2", "2"]
        }],
        "products": [{
            "id": "1",
            "name": "Product 1",
            "description": "Product 1 Description",
            "maximumQuantity": 1,
            "isPeripheral": false,
            "isAvailable": true,
            "price": {
                "upfront": null,
                "installation": "0.00",
                "recurring": "0.00"
            },
            "image": {
                "file": "product-one.png",
            }
        }, {
            "id": "2",
            "name": "Product 2",
            "description": "Product 2 Description",
            "maximumQuantity": null,
            "isPeripheral": true,
            "isAvailable": true,
            "count": 0,  
            "price": {
                "upfront": "60.00",
                "installation": "9.60",
                "recurring": "1.25"
            },
            "image": {
                "file": "product-two.png",
            }
        }, {
            "id": "3",
            "name": "Product Three",
            "description": "Product Three Description",
            "maximumQuantity": null,
            "isPeripheral": true,
            "isAvailable": true,
            "count": 0,  
            "price": {
                "upfront": "132.00",
                "installation": "9.60",
                "recurring": "2.75"
            },
            "image": {
                "file": "product-three.png",
            }
        }]
    }
}

非常感谢任何建议

2 个答案:

答案 0 :(得分:0)

我建议您没有回复,因为您对问题的描述含糊不清:

  

我基本上需要做的是在达到最大输入数量后更新输入的最大值,以便用户无法再向包中添加产品

然后您刚刚将代码转储到页面上。读者现在必须长时间研究代码:

  1. 确定“最大输入数量”变量(您可以将其称为任何内容)。
  2. 确定“输入的最大值”变量。
  3. 了解如何计算这些变量。
  4. 了解它们之间的关系。
  5. 确定所有信息是否在同一范围内。
  6. 了解问题是什么以及为什么你会发现它很困难。
  7. 所有这些可能意味着他们必须创建一个React项目才能了解正在发生的事情。也许一种不同的方法会更好,这样更多的人会花时间阅读这篇文章。请问您的问题和信息更清楚吗?

    由于 安德鲁

答案 1 :(得分:0)

确定找到了解决方案。基本上我只是通过产品进行数组循环并获取总数,然后在添加产品时更新。

var installationTotal = 0;  // Variable to hold your total  
  for(var t = 0, instalen = BundleProducts.length; t < instalen; t++) {
    installationTotal += BundleProducts[t].props.children[19] * BundleProducts[t].props.children[10];  
}
var installTotal = parseFloat(installationTotal, 10).toFixed(2)