简体   繁体   中英

Im getting invalid hook call error with useCallBack in React

im getting invalid hook call error in my project.

 <DateBottomSheet
          key={keyIndexStartDate}
          currentDate={startDate}
          headerTitle={moment(startDate).format('MMMM YYYY')}
          backdropComponent={renderBackdrop}
          ref={sheetRefStartDate}
          snapPoints={snapPointsDateSheet}
          markedDates={markedStartDate}
          onChange={() => handleSheetChanges}
          renderArrow={renderCalendarRightAndLeftIcon}
          onPressArrowRight={()=>onPressCalendarRight(startDate, 'startDate')}
          onPressArrowLeft={()=>onPressCalendarLeft(startDate, 'startDate')}
          onDayPress={day => {
            setMarkedStartDateValue(day.dateString);
            pressOpenStartTimerAction();
            // handleSnapPress(1, CreateWorkyBS.startTime);
          }}
          onPressCancel={() =>
            handleCloseStartCalender(CreateWorkyBS.startDate)
          }
          onPressSave={() => saveStartDateItem()}
          saveButtonDisable={buttonStartDateDisable}></DateBottomSheet>

and is my OnpressCalendar function

const onPressCalendarRight = (date, type) => 
useCallback(add => {
  const addDate = moment(date).add(1, 'M');
  type == 'startDate' ? setStartDate(addDate) : setEndDate(addDate);
  add();
});

Error Screenshoot

Anyone help me?

You are breaking the Rules of Hooks . useCallback is a hook, and as such can ONLY be called at the root level of a functional component.

It looks like you can simply remove the use of useCallback altogether to fix the issue, and call the embedded function directly in onPressCalendarRight .

const onPressCalendarRight = (date, type) => {
  const addDate = moment(date).add(1, 'M');
  type == 'startDate' ? setStartDate(addDate) : setEndDate(addDate);
}

Try this

 onPressCalendarRight = useCallback((add) => (date,type) => {
 const addDate = moment(date).add(1, 'M');
  type == 'startDate' ? setStartDate(addDate) : setEndDate(addDate);
  add();
 },[]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM