简体   繁体   English

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

[英]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并且是我的 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. useCallback是一个钩子,因此只能在功能组件的根级别调用。

It looks like you can simply remove the use of useCallback altogether to fix the issue, and call the embedded function directly in onPressCalendarRight .看起来您可以简单地完全删除useCallback的使用来解决问题,并直接在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();
 },[]);

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

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