防止多次请求和更新

huangapple go评论69阅读模式
英文:

Preventing Multiple Requests and Updating

问题

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

const RoomDetailsPage = ({ route }) => {
  // ...(省略其他代码)

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

    // Only call getOpeningHours when the date is changed
    if (selectedDate !== selectedDate) {
      const hours = await getOpeningHours(selectedDate);
      setOpenHours(hours);
    }

    setSelectedStartHour(null);
    setSelectedEndHour(null);
    setStartHour(null);
    setEndHour(null);
  };

  // ...(省略其他代码)
};

以上代码将在日期更改时调用getOpeningHours函数,以确保仅在日期更改时更新openHours数组。

英文:

In the provided code, there seems to be an issue where the getOpenHours function is being called multiple times in quick succession when a date is selected. Additionally, the openHours Array is being updated with the same value repeatedly. This behavior should be modified to only execute the function when the date is changed, and to update the openHoursArray accordingly. Help is needed to resolve this issue and ensure that the getOpenHours function is only called when the date is changed.
<br>

const RoomDetailsPage = ({ route }) =&gt; {
  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(&quot;T&quot;)[0];
  const endDate =
    roomDetails.days[roomDetails.days.length - 1].date.split(&quot;T&quot;)[0];
  const [openHours, setOpenHours] = useState([]);

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

  const getOpeningHours = async (date) =&gt; {
    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 (
         &lt;View&gt;
            &lt;Text style={styles.subtitle}&gt;Select Date&lt;/Text&gt;
            &lt;Text&gt;Selected Date is {selectedDate}&lt;/Text&gt;
            &lt;DatePicker
            {/* This was imported from &quot;react-native-modern-datepicker&quot; */}
              onSelectedChange={handleDateChange}
              options={{
                backgroundColor: &quot;#090C08&quot;,
                textHeaderColor: &quot;#FFA25B&quot;,
                textDefaultColor: &quot;#F6E7C1&quot;,
                selectedTextColor: &quot;#fff&quot;,
                mainColor: &quot;#F4722B&quot;,
                textSecondaryColor: &quot;#D6C7A1&quot;,
                borderColor: &quot;rgba(122, 146, 165, 0.1)&quot;,
              }}
              current=&quot;2023-06-01&quot;
              mode=&quot;calendar&quot;
              minimumDate={startDate}
              maximumDate={endDate}
              minuteInterval={30}
              style={{ borderRadius: 10 }}
            /&gt;
          &lt;/View&gt;

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

i have tried so many things and i didn't solve the problem , if someone know the problem and how to solve it please tell me.

答案1

得分: 1

你可以尝试在 useEffect 钩子中使用异步函数,就像这样:

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)}
        // 其他属性
    />
)
英文:

you can try using the async function inside a useEffect hook like this:

const [date, setDate] = useState();

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

        const getOpeningHours = async () =&gt; {
            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 &amp;&amp; openHours.length !== 0){
            setOpenHours(openHours);
            setSelectedStartHour(null);
            setSelectedEndHour(null);
            setStartHour(null);
            setEndHour(null);
        }
    }

}, [date])

and inside the return of your component only change the state of the date like this:

return (
    &lt;DatePicker
        onSelectedChange={(value) =&gt; setDate(value)}
        // other props
    /&gt;
)

huangapple
  • 本文由 发表于 2023年6月2日 11:05:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76386893.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定