如何 post 在 React 中使用 react-date-range 请求日期?

How to post request dates with react-date-range in React?

我对 React 比较陌生,想使用 react-date-range 库。为此,我想发送一个带有 axios 开始日期和结束日期的 POST 请求。但是,我在结合库和 post 请求时遇到问题。有人可以帮我解决这个问题吗?因为现在开始日期和结束日期都没有提交,我不知道该怎么办。

import React, { Component, useState } from 'react';
import './Datepickersearch.css';
import 'react-date-range/dist/styles.css'; // main style file
import 'react-date-range/dist/theme/default.css'; //theme css file
import { DateRangePicker } from 'react-date-range';
import { Button } from '@material-ui/core';
import { useHistory } from 'react-router-dom';
import axios from 'axios';

function Search() {
  const history = useHistory();
  const [startDate, setStartDate] = useState(new Date());
  const [endDate, setEndDate] = useState(new Date());

  const selectionRange = {
    startDate: startDate,
    endDate: endDate,
    key: 'selection',
  };

  function handleSelect(ranges) {
    setStartDate(ranges.selection.startDate);
    setEndDate(ranges.selection.endDate);
  }

  axios.post(`http://localhost:8080/api/reservation/`, { startDate, endDate }).then((res) => {
    console.log(res);
    console.log(res.data);
  });

  return (
    <div className="datepickersearch">
      <DateRangePicker ranges={[selectionRange]} onChange={handleSelect} />

      <h2> Number of guests</h2>
      <input min={0} defaultValue={2} max={7} type="number" />
      <Button onClick={() => history.push('/search')}>Search Apartments</Button>
    </div>
  );
}

export default Search;

您需要在按钮上添加 onClick 方法,并调用一个方法来 post 数据、日期正在填充(检查控制台语句)。

请检查此代码 - https://codesandbox.io/s/axios-post-data-dhded?file=/src/Search.jsx