redux 常见函数中使用的React Hook“useError”抛出错误

v09wglhw  于 5个月前  发布在  React
关注(0)|答案(1)|浏览(62)

这是我的selectors.js
第一个月
export const useCloseAlertTrigger = () => useSelector((state) => state.common.closeAlertTrigger || {});
这是我的commonFunction.js[在这里我存储了我的所有常用函数]

export const LogoutUser = async () => {
  const closeAlert = useCloseAlertTrigger();
  if (closeAlert) {
    const result = await DisplayMessageOnClosebookingEdit();
    if (result) {
      return false;
    }
  }
  const result = await RCM_API(
    'POST',
    '',
    {
      service: 'service',
      action: 'logout',
    },
    true
  );
  if (result && result.resultCode === STATUS.SUCCESS) {
    window.location.href = `${window.location.origin}/${BASE_PATH}/logout`;
  }
  return true;
};

字符串
在这个函数中,我使用了useCloseAlertTriggerhook,但是react抛出了一个错误,即hook只能在组件内部调用的函数中调用,如果我使用简单函数而不是hook,则会出现另一个错误,例如useselctor只能在组件内部使用或react hook,这就是为什么我必须给予前缀use
PS:英语不好
我想让redux架构通用,比如我将在selector.js中创建选择器函数,我将在commonfunction.js中使用该选择器,然后我将在组件PS中使用相应的函数:我使用redux-toolkit

ohtdti5x

ohtdti5x1#

请尝试,您不能在函数中使用选择器

export const LogoutUser = async (closeAlert) => {
  if (closeAlert) {
    const result = await DisplayMessageOnClosebookingEdit();
    if (result) {
      return false;
    }
  }

  const result = await RCM_API(
    'POST',
    '',
    {
      service: 'service',
      action: 'logout',
    },
    true
  );
  if (result && result.resultCode === STATUS.SUCCESS) {
    window.location.href = `${window.location.origin}/${BASE_PATH}/logout`;
  }
  return true;
};

// in the component
const closeAlert = useCloseAlertTrigger();

// whereever you call the logout function
LogoutUser(closeAlert)

// or use an useEffect
useEffect(() => {
  if (closeAlert) {
  LogoutUser(closeAlert)  
  }
},[closeAlert])

字符串

相关问题