javascript 防止多个请求和更新

ohtdti5x  于 2023-06-04  发布在  Java
关注(0)|答案(1)|浏览(127)

在所提供的代码中,似乎存在一个问题,即当选择一个日期时,getOpenHours函数会被快速连续地调用多次。此外,openHours数组会重复更新相同的值。此行为应修改为仅在日期更改时执行函数,并相应地更新openHoursArray。需要帮助来解决此问题并确保仅在日期更改时调用getOpenHours函数。

const RoomDetailsPage = ({ route }) => {
  const [selectedDate, setSelectedDate] = useState(null);
  const [selectedStartHour, setSelectedStartHour] = useState(null);
  const [selectedEndHour, setSelectedEndHour] = useState(null);
  const [startHour, setStartHour] = useState(null);
  const [endHour, setEndHour] = useState(null);
  const [isDatePickerVisible, setDatePickerVisible] = useState(false);
  const { roomId } = route.params;
  const { placeId } = route.params;
  const { roomDetails } = route.params;
  const startDate = roomDetails.days[0].date.split("T")[0];
  const endDate =
    roomDetails.days[roomDetails.days.length - 1].date.split("T")[0];
  const [openHours, setOpenHours] = useState([]);

  const handleDateChange = async (date) => {
    const formattedDate = date.replace(/\//g, "-");
    const selectedDate = new Date(formattedDate);
    const hours = await getOpeningHours(selectedDate);
    setOpenHours(hours);
    setSelectedStartHour(null);
    setSelectedEndHour(null);
    setStartHour(null);
    setEndHour(null);
  };

  const getOpeningHours = async (date) => {
    try {
      const response = await axios.post(
        `https://spacezone-backend.cyclic.app/api/booking/getOpenHours/${placeId}`,
        { Date: date }
      );
      return response.data.openHoursArray;
    } catch (error) {
      console.log(error);
      return [];
    }
  };
return (
         <View>
            <Text style={styles.subtitle}>Select Date</Text>
            <Text>Selected Date is {selectedDate}</Text>
            <DatePicker
            {/* This was imported from "react-native-modern-datepicker" */}
              onSelectedChange={handleDateChange}
              options={{
                backgroundColor: "#090C08",
                textHeaderColor: "#FFA25B",
                textDefaultColor: "#F6E7C1",
                selectedTextColor: "#fff",
                mainColor: "#F4722B",
                textSecondaryColor: "#D6C7A1",
                borderColor: "rgba(122, 146, 165, 0.1)",
              }}
              current="2023-06-01"
              mode="calendar"
              minimumDate={startDate}
              maximumDate={endDate}
              minuteInterval={30}
              style={{ borderRadius: 10 }}
            />
          </View>

          {/* List of selectable hours */}
          {openHours && openHours.length > 0 ? (
            <>
              <Text style={styles.subtitle}>Select Hours</Text>
              <View style={styles.hoursContainer}>
                {openHours.map((hour) => (
                  <TouchableOpacity
                    key={hour}
                    style={[
                      styles.hourCard,
                      hour === selectedStartHour || hour === selectedEndHour
                        ? styles.selectedHourCard
                        : null,
                    ]}
                    onPress={() => handleHourPress(hour)}
                  >
                    <Text>{hour}:00</Text>
                  </TouchableOpacity>
                ))}
              </View>
            </>
          ) : (
            <Text>Loading open hours...</Text>
          )}
        </View>
);

我已经尝试了很多东西,我没有解决这个问题,如果有人知道这个问题,并如何解决它,请告诉我。

0sgqnhkj

0sgqnhkj1#

你可以尝试在useEffect钩子中使用async函数,如下所示:

const [date, setDate] = useState();

useEffect(() => {
    if (date){
        const formattedDate = date.replace(/\//g, "-");
        const selectedDate = new Date(formattedDate);

        const getOpeningHours = async () => {
            try {
              const response = await axios.post(
                `https://spacezone-backend.cyclic.app/api/booking/getOpenHours/${placeId}`,
                { Date: date }
              );
               setOpenHours(response.data.openHoursArray);
            } catch (error) {
              console.log(error);
            }
          };

        getOpeningHours();
    
        if(openHours && openHours.length !== 0){
            setOpenHours(openHours);
            setSelectedStartHour(null);
            setSelectedEndHour(null);
            setStartHour(null);
            setEndHour(null);
        }
    }

}, [date])

在组件的返回值中只修改日期的state如下:

return (
    <DatePicker
        onSelectedChange={(value) => setDate(value)}
        // other props
    />
)

相关问题