在HOC中使用带有传递参数的react钩子

时间:2020-04-30 07:38:46

标签: reactjs react-hooks react-hoc

我正在尝试创建HOC并在其中使用自定义react钩子。另外,为了使用钩子,我需要将paras传递给HOC,但是仅在函数体中使用钩子会出错。我的HOC是:

export const withUseAxisTranslate = (props) => {
  const [t] = useAxisTranslate(props.namespace);
  return (WrappedComponent) => (moreProps) => <WrappedComponent {...moreProps} t={t} />;
};

我的useAxisTranslate看起来像:

import { useSelector } from 'react-redux';
import { useTranslation } from 'react-i18next';

//This one is behave like regular i18 translate
//It returns like t() in array function and use axis name in order to find specific key by axis name
const useAxisTranslate = (namespace) => {
  return [
    (stringToTranslate) => {
      const axisName = useSelector((state) => state.axisConfig.axis.name.toLowerCase());
      const [t] = useTranslation(namespace);
      return t(`${axisName}.${stringToTranslate}`);
    },
  ];
};

export default useAxisTranslate;

我的电话是:

compose(
  withWidth(),
  withUseAxisTranslate({ namespace: 'header' }),
)(MyComponent);

我得到的错误是:

enter image description here

我不知道为什么会收到此错误,因为我不在这里使用类 感谢您的帮助

2 个答案:

答案 0 :(得分:3)

这里有几件事要注意

  • 您正在尝试使用import numpy as np import pandas as pd df = pd.DataFrame({ 'Quarters' :['2000q1','2000q2','2000q3','2OOOq4','2001q1','2001q2','2001q3'], 'Growth' : [np.nan,10,20,-5,-6,10,-8]}) flag=0 for index, rows in df.iterrows(): if rows['Growth']<0 and flag<0: print(rows['Quarters']) break flag=rows['Growth'] ,它是useAxisTranslate中的自定义钩子,它不是组件,而是返回另一个函数的函数。
  • 您在返回的函数内部的自定义钩子中使用withUseAxisTranslateuseSelector,这再次违反了规则

这里的解决方案是纠正以下两种情况

useTranslation

并使用AxisTranslate作为

export const withUseAxisTranslate = (props) => {
  return (WrappedComponent) => (moreProps) => {
        const [t] = useAxisTranslate(props.namespace);
        return <WrappedComponent {...moreProps} t={t} />
  }
};

答案 1 :(得分:0)

尝试像这样将useAxisTranslate钩子移动到组件主体内部

export const withUseAxisTranslate = (props) => {
    return (WrappedComponent) => (moreProps) => {
        const [t] = useAxisTranslate(props.namespace);
        return <WrappedComponent {...moreProps} t={t} />;
    }
};
相关问题