如何使用DataPicker筛选数据并在ReactJs中获取总计

0ve6wy6x  于 2022-12-12  发布在  React
关注(0)|答案(1)|浏览(123)

我有一个过滤器类组件。但是当我选择两个日期并单击onsubmit搜索按钮时,我得到的是所有数据,而不是所选日期的数据。此外,当我添加getTotal函数时,我得到了一个空白页,并在const filteredCustomers = this.customers.filter(function(a){.......处出现过滤器错误。我希望能够按两个日期选择数据,并能够根据所选日期得到总数。
Json数据

customers:[
        {
          "_id": "6389d19a3b28b9e4af3694f8",
          "fullName": "WADE IVAN",
          "clientdetails": {
            "_id": "6389d1193b28b9e4af3694f2",
            "dateofBirth": "1990-01-01T00:00:00.000Z",
            "age": 32,
            "__v": 0
          },
          "paymentReferenceCode": "1",
          "paymentType": "Cash",
          "paymentDescription": "ACCOMODATION",
          "procedureAmount": "100",
          "paymentDiscount": 20,
          "AmountPaid": 100,
          "totals": 100,
          "date": "Jan 20, 2022",
          "__v": 0
        },
        {
          "_id": "6389d1bb3b28b9e4af369500",
          "fullName": "WADE IVAN",
          "clientdetails": {
            "_id": "6389d1193b28b9e4af3694f2",
            "dateofBirth": "1990-01-01T00:00:00.000Z",
            "age": 32,
            "__v": 0
          },
          "paymentReferenceCode": "12",
          "paymentType": "Cash",
          "paymentDescription": "ACCOMODATION",
          "procedureAmount": "100",
          "paymentDiscount": 20,
          "AmountPaid": 80,
          "totals": 80,
          "date": "Jan 18, 2020",
          "__v": 0
        },
        {
          "_id": "6389d1e03b28b9e4af369508",
          "fullName": "JOHN MARK",
          "clientdetails": {
            "_id": "6389d0ed3b28b9e4af3694ee",
            "dateofBirth": "2000-01-12T00:00:00.000Z",
            "age": 22,
            "__v": 0
          },
          "paymentReferenceCode": "3",
          "paymentType": "Cash",
          "paymentDescription": "100",
          "procedureAmount": "100",
          "paymentDiscount": 20,
          "AmountPaid": 200,
          "totals": 200,
          "date": "Jan 20, 2018",
          "__v": 0
        },
        {
          "_id": "6389d2173b28b9e4af369510",
           "fullName": "JOHN MARK",
          "clientdetails": {
            "_id": "6389d0ed3b28b9e4af3694ee",
            "dateofBirth": "2000-01-12T00:00:00.000Z",
            "age": 22,
            "__v": 0
          },
          "paymentReferenceCode": "9",
          "paymentType": "Cash",
          "paymentDescription": "ACCOMODATION",
          "procedureAmount": "10",
          "paymentDiscount": 2,
          "AmountPaid": 300,
          "totals": 300,
          "date": "Dec 15, 2021",
          "__v": 0
        },
        {
          "_id": "6389d2173b28b9e4af369512",
          "fullName": "JOHN MARK",
          "clientdetails": {
            "_id": "6389d0ed3b28b9e4af3694ee",
            "dateofBirth": "2000-01-12T00:00:00.000Z",
            "age": 22,
            "__v": 0
          },
          "paymentReferenceCode": "9",
          "paymentType": "Cash",
          "paymentDescription": "ACCOMODATION",
          "procedureAmount": "10",
          "paymentDiscount": 2,
          "AmountPaid": 300,
          "totals": 300,
          "date": "Feb 20, 2019",
          "__v": 0
        }
      ]

当前代码:

export default class Customer extends React.Component{
      constructor(){
        super();
        this.state={
        customers:[],
        date:"",
        totals:""
      }
      }
      onsubmit = (e) => {    

        const customers = { startDate:this.state.startDate, endDate:this.state.endDate};    

        e.preventDefault();    

        axios.get('http://localhost:4000/customers',customers).then(response => {  

            console.log(response.data);  

            this.setState({  

                customers: response.data  

            });  

        });  

    }     
    Changedate = (e) => {    

      this.setState({    

              startDate: e    

      });    

    };  

    endDate = (e) => {    

    this.setState({    

      endDate: e    

    })    

    function getTotal(customers) {
      try {
        const reduced = customers?.reduce((acc, curr) => {
          const prop = curr._id;
          const existingTotal = acc?.[prop]?.total ?? 0;
          console.log(acc, acc?.[prop]);
          console.log(acc, curr.fullName);
        
          return {
            ...acc,
            [prop]: {
              id: prop,
              name: curr.fullName,
              total: existingTotal + curr.totals
            }
          };
        }, {}
        );

        const total = Object.entries(reduced).reduce((acc, [key, value]) => {
          return acc + value.total 
        
        }, 0);
        return total;
      } catch (error) {
        console.log("error", error);
        return 0;
      }
    }

    }
      
      render(){
        const {customers, getTotal} = this.props;
        const startDate = new Date();
        const endDate = new Date();
        const cDate = new Date(); 
        //const filteredCustomers = this.customers.filter(function(a){
          //cDate = new Date(a.date);
          //return cDate >= startDate && cDate <= endDate;});
        //console.log(filteredCustomers)   

        return (
          <div>  

                    <div className="row">  

                        <div className="col-sm-12">  

                            Search for Customers and Total Revenue By Selected Dates

                    </div>  

                    </div>  

                    <form onSubmit={this.onsubmit}>  

                        <div className="row hdr" >  

                            <div className="col-sm-3 form-group">  </div>  

                            <div className="col-sm-3 form-group">  

                                    <DatePicker className="form-control"    

                                                            selected={this.state.startDate} placeholderText="Select Date" showPopperArrow={false}    

                                                            onChange={this.Changedate}    

                                                    />    

                            </div>  

                            <div className="col-sm-3 form-group">  

                                    <DatePicker className="form-control"    

                                                            selected={this.state.endDate} placeholderText="Select Date" showPopperArrow={false}    

                                                            onChange={this.endDate}    

                                                    />    
                            </div>  

                            <div className="col-sm-3 form-group">  

                                <button type="submit" className="btn btn-success" >Search</button>  

                            </div>  

                        </div>  

                    </form>  

                    <table className="table">  

                        <thead className="thead-dark">  

                            <tr>  

                                <th scope="col">Id</th>  
                                <th scope="col">Date</th>  
                                <th scope="col">Name</th>  
                                <th scope="col">Payment Description</th> 
                                <th scope="col">Bill</th>  
                            </tr>  
                        </thead>  

                        <tbody>  

                            {  

                        this.state.customers.map((a, index) => {  

                          return  <tr key={index}>  

                          
                                <td>{a.date}</td>  
                                <td>{a.name}</td>  
                                <td>{a.paymentDescription}</td>  
                                <td>{a.totals}</td>  
                              {/*} <td>{total}</td> */}
                            </tr>  

                        })   
                        }  
                        </tbody>  
                    </table>  
                </div>
        )
      }

    }

我怎样才能更正这个代码我是新的编码。我真的很感谢你能提供任何帮助。

zzwlnbp8

zzwlnbp81#

这是工作代码。

import "./styles.css";
import "react-datepicker/dist/react-datepicker.css";
import React from "react";
import axios from "axios";
import DatePicker from "react-datepicker";

export default class Customer extends React.Component {
  constructor() {
    super();
    this.state = {
      customers: [],
      date: [],
      total: 0
    };
  }
  onsubmit = (e) => {
    const date = {
      startDate: this.state.startDate,
      endDate: this.state.endDate
    };
    e.preventDefault();
    try {
      axios.get("./customers.json", date).then((response) => {
        this.setState({
          customers: response.data.customers,
          total: this.getTotal(response.data.customers)
        });
      });
    } catch (e) {
      console.error(e);
    }
  };

  startDate = (e) => {
    this.setState({
      startDate: e
    });
  };

  endDate = (e) => {
    this.setState({
      endDate: e
    });
  };

  getTotal = (customers) => {
    try {
      const reduced = customers?.reduce((acc, curr) => {
        const prop = curr._id;
        const existingTotal = acc?.[prop]?.total ?? 0;

        return {
          ...acc,
          [prop]: {
            id: prop,
            name: curr.fullName,
            total: existingTotal + curr.totals
          }
        };
      }, {});

      const total = Object.entries(reduced).reduce((acc, [key, value]) => {
        return acc + value.total;
      }, 0);
      return total;
    } catch (error) {
      console.log("error", error);
      return 0;
    }
  };

  render() {
    const { customers } = this.state;
    const filteredCustomers = customers.filter((c) => {
      let cDate = new Date(c.date);
      const startDate = new Date(this.state.startDate);
      const endDate = new Date(this.state.endDate);

      return (
        cDate.getTime() >= startDate.getTime() &&
        cDate.getTime() <= endDate.getTime()
      );
    });

    let total = this.getTotal(filteredCustomers);

    return (
      <div>
        <div className="row">
          <div className="col-sm-12">
            <h2>Search for Customers and Total Revenue By Selected Dates</h2>
          </div>
        </div>

        <form onSubmit={this.onsubmit}>
          <div className="row hdr">
            <div className="col-sm-3 form-group"> </div>

            <div className="col-sm-3 form-group">
              <DatePicker
                className="form-control"
                selected={this.state.startDate}
                placeholderText="Select Start Date"
                showPopperArrow={false}
                onChange={this.startDate}
              />
            </div>

            <div className="col-sm-3 form-group">
              <DatePicker
                className="form-control"
                selected={this.state.endDate}
                placeholderText="Select End Date"
                showPopperArrow={false}
                onChange={this.endDate}
              />
            </div>

            <div className="col-sm-3 form-group">
              <button type="submit" className="btn btn-success">
                Search
              </button>
            </div>
          </div>
        </form>

        <table className="table">
          <thead className="thead-dark">
            <tr>
              <th scope="col">Id</th>
              <th scope="col">Date</th>
              <th scope="col">Name</th>
              <th scope="col">Payment Description</th>
              <th scope="col">Bill</th>
            </tr>
          </thead>

          <tbody>
            {filteredCustomers.map((customer, index) => {
              return (
                <tr key={index}>
                  <td>{customer._id}</td>
                  <td>{customer.date}</td>
                  <td>{customer.fullName}</td>
                  <td>{customer.paymentDescription}</td>
                  <td>{customer.totals}</td>
                </tr>
              );
            })}

            {filteredCustomers.length > 0 && (
              <tr>
                <td></td>
                <td></td>
                <td></td>
                <td>total</td>
                <td>{total}</td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    );
  }
}

您可以在此处查看工作演示。https://codesandbox.io/s/crazy-danny-wgsgro?file=/src/App.js

相关问题