【问题标题】:NextJS this.props + React Toast NotificationNextJS this.props + React Toast 通知
【发布时间】:2019-01-24 10:00:05
【问题描述】:

我正在使用 NextJS 和 React Toast Notifications 开发一个带有 SSR 的反应应用程序。该软件包要求我用 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 并且仍然保留通知包。

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    我认为您需要在 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} />;
            }
        };
    }
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2016-09-26
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-19
      • 2021-02-25
      相关资源
      最近更新 更多