将装饰器更改为 HOC,HOC 返回功能组件,而不是使用 getInitialProps 的类下一个 v10

问题描述

我有两个任务:

  1. 用 HOC 替换装饰器
  2. 是否可以构建一个返回纯函数而不是类的 HOC?多少有意义,速度会显着提高吗?

// _app.js

   @myDecorator(SelfClassForSaga,['str1','str2'])
   class MyApp extends App {
     static async getinitialProps({Component,ctx}) {
        await ctx.store.stopSaga();
        await ctx.store.execSagaTasks(ctx,dispatch => {
            dispatch(SelfClassForSaga.actions.str1());
        });
        const pageProps = Component.getinitialProps ? await Component.getinitialProps(ctx) : {};
        return {pageProps};
     }
     render() {...}
   }
   export default MyApp;

// myDecorator

export const myDecorator = (SelfClassForSaga,StrArr) => (Component) => {}

我想用 HOC 替换装饰器,以便 _app 组件本身可以成为一个函数

// HOC(我如何让 HOC 返回“Class”):

export const myHOC = (WrappedComponent,SelfClassForSaga,strArr) => {
    class WithHOC extends React.Component {
       constructor(props) {
          super(props);
       }
       public static async getinitialProps(ctx) {
          return WrappedComponent.getinitialProps ? await WrappedComponent.getinitialProps(ctx) : {};
       }

       // logic from old decorator(myDecorator) for SelfClassForSaga and StrArr

       public render() {
         return (
            <WrappedComponent {...this.props} />
         );
       }
    }
}

我想用这个函数做:

const myHOC = (WrappedComponent,StrArr) => ({...props}) => {
   return <WrappedComponent {...props}/>
}

并相应地更改 _app.js 中的导出:

const WrappedApp = myHOC(MyApp,'str2']);
export default WrappedApp;

当然!,我得到一个错误,因为我没有在函数调用 getinitialProps :

TypeError: Cannot read property 'execSagaTasks' of undefined (ctx is missing)

事实是/pages中的页面也被HOC包裹,在浏览器中也说没有ctx

如何正确调用 getinitialProps 并进一步返回包装的组件? 感谢您的帮助!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)