NextJS this.props + React Toast通知

时间:2019-01-24 10:00:06

标签: reactjs next.js

我正在使用NextJS和 React Toast Notifications使用SSR开发一个React应用程序。该包装要求我用HOC包装组件。

export default withToastManager(developersEdit);

但是用HOC封装它不再允许我访问NextJS this.props。我怎么仍然可以在我的应用程序中使用NextJS道具?

我尝试使用传播操作符进行导出

export default withToastManager(developersEdit ...this.props);

但这没用

import React, { Component } from 'react';
import { withToastManager } from 'react-toast-notifications';
import getConfig from 'next/config';
import fetch from 'isomorphic-unfetch';

class developersEdit extends Component  {
  constructor(props) {
    super(props);
    this.state = {
      backgroundImg: 'https://'+this.props.environment.API_URL+'.xyz.com/'+this.props.currentDeveloper.developer_logo,
    }
  }


  static async getInitialProps (context) {

    const { slug } = context.query;
    const {publicRuntimeConfig} = getConfig()

    const resDeveloper = await fetch(`https://${publicRuntimeConfig.API_URL}.xyz.com/api/showdeveloper/${slug}`)
    const developer = await resDeveloper.json()

    console.log(developer);
    return {
        currentDeveloper: developer.data,
        environment: publicRuntimeConfig,
        slug: slug
    }

  }
}

                ......

export default withToastManager(developersEdit);

我希望能够使用this.props并仍然保留通知包。

1 个答案:

答案 0 :(得分:0)

我认为您需要像下面的示例一样在HOC中实现getInitialProps()和render()方法:

export default function withToastManager(WrappedComponent, options = {}) {

    return class extends React.Component {
        constructor(props) {
            super(props);
        }

        static async getInitialProps(ctx) {
            const getInitialProps = WrappedComponent.getInitialProps;
            let data = {};
            if (ctx.req) {
                // server side code
                data = ctx.req.session.data; 
            } else {
                // client side code        
                data = ctx.data;
            }

            let props = {};
            if (getInitialProps) {
                props = await getInitialProps({...ctx, ...data});
            }

            return props;
        }

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

希望它对您有帮助。

相关问题