Warm tip: This article is reproduced from serverfault.com, please click

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

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

发布于 2020-11-30 15:30:19

我是一个相对较新的 React 者,想使用该react-date-range库。为此,我想发送一个POST包含axios开始日期和结束日期请求但是,我在合并库和发布请求时遇到问题。有人可以帮我解决这个问题吗?因为现在开始日期和结束日期尚未提交,我也不知道该怎么办。

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;
Questioner
lara-div
Viewed
11
Madhuri 2020-12-01 02:02:14

你需要在按钮上添加onClick方法,并调用一种方法来发布数据,然后填充日期(检查控制台语句)。

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