繁体   English   中英

我在 React 中使用 useCallBack 收到无效的钩子调用错误

[英]Im getting invalid hook call error with useCallBack in React

我在我的项目中遇到无效的钩子调用错误。

 <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>

并且是我的 OnpressCalendar function

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

错误截图

有人帮我吗?

你违反了钩子规则 useCallback是一个钩子,因此只能在功能组件的根级别调用。

看起来您可以简单地完全删除useCallback的使用来解决问题,并直接在onPressCalendarRight

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

尝试这个

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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