【问题标题】:To get differnce in days and store in variable获取天数差异并存储在变量中
【发布时间】:2021-11-24 09:20:15
【问题描述】:

我正在尝试将天差与其他数据一起发送到 POST 网址。

表单有 2 个日期字段,应在“保存”数据时计算天数差异。

<div className = "form-group">
  <label>Booking Day</label>
  <input type="date" id = "bookingDate" placeholder="Booking Date..." name="bookingDate" 
    className="form-control" value={this.state.bookingDate} onChange= 
    {this.changeBookingDateHandeler}/>
</div>
<br />
<div className = "form-group">
  <label>Check Out Date</label>
  <input type="date" id = "checkOutDate" placeholder="Check Out Date..." name="checkOutDate" 
    className="form-control" value={this.state.checkOutDate} onChange= 
    {this.changeCheckoutDateHandeler}/>
</div>
<br />
<button className="btn btn-primary" onClick = {this.saveGuests}>Save</button>

保存功能

saveGuests = (e) => {
    e.preventDefault();
    //difference is days
    const _MS_PER_DAY = 1000 * 60 * 60 * 24;
    function dateDifference(){
      const bookingDate = this.state.bookingDate;
      const checkOutDate = this.state.checkOutDate;
      const utc1 = Date.UTC(checkOutDate.getDay());
      const utc2 = Date.UTC(bookingDate.getDay());
      return Math.floor((utc2 - utc1) / _MS_PER_DAY);
    }
    const days = dateDifference();
    //payload
    let guest = {
      lastName : this.state.lastName,
      firstName : this.state.firstName,
      rooms : this.state.rooms,
      bookingDate: this.state.bookingDate,
      checkOutDate: this.state.checkOutDate,
      days: days,
    };
    console.log('guest =>' + JSON.stringify(guest));
    //sending post request
    HotelBookService.createGuests(guest).then(res => {
      this.props.history.push('/HotelBook');
    });
  }

但是,它显示了在 dateDifference() 中声明的这 2 个 consts (bookingDate, checkOutDate) 的状态错误

TypeError: Cannot read properties of undefined (reading 'state')

这是完整的文件

import React, { Component } from 'react'
import HotelBookService from '../services/HotelBookService';
class CreateGuests extends Component{
  constructor(props){
    super(props)
    this.state = {
      lastName:'',
      firstName:'',
      rooms:'',
      bookingDate:'',
      checkOutDate:'',
      days: '',
    }
    this.cancel_add_guests = this.cancel_add_guests.bind(this);
    this.changeLastNameHandeler = this.changeLastNameHandeler.bind(this);
    this.changeFirstNameHandeler = this.changeFirstNameHandeler.bind(this);
    this.changeRoomsHandeler = this.changeRoomsHandeler.bind(this);
    this.changeBookingDateHandeler = this.changeBookingDateHandeler.bind(this);
    this.changeCheckoutDateHandeler = this.changeCheckoutDateHandeler.bind(this);
    this.saveGuests = this.saveGuests.bind(this);
  }
  cancel_add_guests(){
    this.props.history.push('/HotelBook');
  }
  changeLastNameHandeler = (event) => {
    this.setState({lastName : event.target.value});
  }
  changeFirstNameHandeler = (event) => {
    this.setState({firstName : event.target.value});
  }
  changeRoomsHandeler = (event) => {
    this.setState({rooms : event.target.value});
  }
  changeBookingDateHandeler = (event) => {
    this.setState({bookingDate : event.target.value});
  }
  changeCheckoutDateHandeler = (event) => {
    this.setState({checkOutDate : event.target.value});
  }
  saveGuests = (e) => {
    e.preventDefault();
    //difference is days
    const _MS_PER_DAY = 1000 * 60 * 60 * 24;
    function dateDifference(){
      const bookingDate = this.state.bookingDate;
      const checkOutDate = this.state.checkOutDate;
      const utc1 = Date.UTC(checkOutDate.getDay());
      const utc2 = Date.UTC(bookingDate.getDay());
      return Math.floor((utc2 - utc1) / _MS_PER_DAY);
    }
    const days = dateDifference();
    //payload
    let guest = {
      lastName : this.state.lastName,
      firstName : this.state.firstName,
      rooms : this.state.rooms,
      bookingDate: this.state.bookingDate,
      checkOutDate: this.state.checkOutDate,
      days: days,
    };
    console.log('guest =>' + JSON.stringify(guest));
    //sending post request
    HotelBookService.createGuests(guest).then(res => {
      this.props.history.push('/HotelBook');
    });
  }
  render(){
    return(
        <div>
          <div className = "container-fluid"><button type="buton" className="btn btn-primary" onClick = {this.cancel_add_guests}>Back</button></div>
          <div className="container">
            <div className="row">
              <div className="card col-md-6 offset-md-3 offset">
                <h3 className="text-center">Add Guests</h3>
                <div className="card-body">
                  <form>
                    <div className = "form-group">
                      <label>Last Name</label>
                      <input type="text" placeholder="Surname..." name="lastName" className="form-control" value={this.state.lastName} onChange={this.changeLastNameHandeler}/>
                    </div>
                    <br />
                    <div className = "form-group">
                      <label>First Name</label>
                      <input type="text" placeholder="Name..." name="firstName" className="form-control" value={this.state.firstName} onChange={this.changeFirstNameHandeler}/>
                    </div>
                    <br />
                    <div className = "form-group">
                      <label>Rooms</label>
                      <input type="number" placeholder="Rooms..." name="rooms" className="form-control" value={this.state.rooms} onChange={this.changeRoomsHandeler}/>
                    </div>
                    <br />
                    <div className = "form-group">
                      <label>Booking Day</label>
                      <input type="date" id = "bookingDate" placeholder="Booking Date..." name="bookingDate" className="form-control" value={this.state.bookingDate} onChange={this.changeBookingDateHandeler}/>
                    </div>
                    <br />
                    <div className = "form-group">
                      <label>Check Out Date</label>
                      <input type="date" id = "checkOutDate" placeholder="Check Out Date..." name="checkOutDate" className="form-control" value={this.state.checkOutDate} onChange={this.changeCheckoutDateHandeler}/>
                    </div>
                    <br />
                    <button className="btn btn-primary" onClick = {this.saveGuests}>Save</button>&nbsp; &nbsp;
                    <button className="btn btn-outline-primary" onClick = {this.cancel_add_guests}>Cancel</button>
                  </form>
                </div>
              </div>
            </div>
          </div>
        </div>
    );
  }
}
export default CreateGuests;

除了负载中的days 字段外,其他字段都工作正常。

请建议,我将如何计算日差并将其与其他人一样发送到 URL。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您在没有前导父对象的普通函数中使用此关键字。

     function dateDifference(){
          const bookingDate = this.state.bookingDate;
          const checkOutDate = this.state.checkOutDate;
          const utc1 = Date.UTC(checkOutDate.getDay());
          const utc2 = Date.UTC(bookingDate.getDay());
          return Math.floor((utc2 - utc1) / _MS_PER_DAY);
        }
        const days = dateDifference();
    

    这里调用 dateDifference 时不带任何前导对象,当我们在函数内部使用 this 关键字访问时,会导致 undefined。

    您可以通过以下方式绑定函数调用

       const days = dateDifference.bind(this);
    

    或者你可以使用箭头函数,因为它会检查词法范围。

     const dateDifference=()=>{
              const bookingDate = this.state.bookingDate;
              const checkOutDate = this.state.checkOutDate;
              const utc1 = Date.UTC(checkOutDate.getDay());
              const utc2 = Date.UTC(bookingDate.getDay());
              return Math.floor((utc2 - utc1) / _MS_PER_DAY);
            }
            const days = dateDifference();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多