UseState钩子在本机反应中不起作用

时间:2020-07-25 17:01:06

标签: javascript react-native react-hooks react-native-calendars

我正在尝试使用react-native-calendars设置日历的开始日期和结束日期。由于某些原因,setStartDate和setEndDate无法正常工作。选择日历上的日期时,我试图设置开始日期或结束日期。在setDate函数下,将根据不同条件设置日期。设置日期后,我将创建一个日期范围。但是,未在startDate或endDate中设置所选日期。谁能指出我做错了什么?谢谢。

export function ArrivedCalendar() {
   const [startDate, setStartDate] = useState("2020-07-24")
   const [endDate, setEndDate] = useState("2020-07-31")
   const [markedDates, setMarkedDates] = useState({});

   const setDate = (selectedDate) => {

    console.log(selectedDate);
      if (
        selectedDate.timestamp < new Date(startDate).getTime() &&
        selectedDate.timestamp < new Date(endDate).getTime()) {
         setStartDate(selectedDate.dateString);
         console.log(startDate);
         console.log(1)
      } else if (
         new Date(startDate).getTime() < selectedDate.timestamp &&
         selectedDate.timestamp < new Date(endDate).getTime()) {
          console.log(selectedDate.dateString);
          setStartDate(selectedDate.dateString)
          console.log(startDate);
          console.log(2);
      } else if (new Date(startDate).getTime() < selectedDate.timestamp &&
         new Date(endDate).getTime() < selectedDate.timestamp) {
          setEndDate(selectedDate.dateString);
          
          console.log("start", startDate);
          console.log("end", endDate);

          console.log(3);
      }
   }

   const generateSelectedDates = () => {

      var dateArray = {}
      var currentDate = moment(startDate)
      // console.log(currentDate.format("YYYY-MM-DD"));
      while (currentDate <= endDate) {
        console.log(moment(currentDate).format("YYYY-MM-DD"));
        dateArray[moment(currentDate).format("YYYY-MM-DD")] = {
          color: "#87CEEB",
        };
        currentDate = moment(currentDate).add(1, "days")
      }

      console.log(dateArray)
      //Update the period after generating the date
      setMarkedDates(dateArray);
   }

   return (
     <View>
       <Calendar
         minDate={Date()}
         onDayPress={(day) => {
          //  console.log("selected day", day)
           setDate(day)
           generateSelectedDates()
         }}
         markedDates={{
           [startDate]: {
             selected: true,
             color: "#87CEEB",
             startingDay: true,
           },
           [endDate]: {
             selected: true,
             color: "#87CEEB",
             endingDay: true,
           },
         }}
         markingType={"period"}
       />
     </View>
   );
}

0 个答案:

没有答案