使用 HOC 访问在 Next.js getInitialProps 中消耗的 React.Context

Accessing consumed React.Context in Next.js getInitialProps using HOC

我试图通过使用提供非常简单方法的简单服务来抽象我的 API 调用,这只是一个 HTTP 调用。我将此实现存储在 React 上下文中,并在我的 _app.js 中使用其提供程序,以便 API 全局可用,但我在实际使用页面中的上下文时遇到问题。

pages/_app.js

import React from 'react'
import App, { Container } from 'next/app'

import ApiProvider from '../Providers/ApiProvider';

import getConfig from 'next/config'
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()

export default class Webshop extends App 
{
    static async getInitialProps({ Component, router, ctx }) {
        let pageProps = {}

        if (Component.getInitialProps) {
            pageProps = await Component.getInitialProps(ctx)
        }

        return { pageProps }
    }

    render () {
        const { Component, pageProps } = this.props

        return (
            <Container>
                <ApiProvider endpoint={publicRuntimeConfig.api_endpoint}>
                    <Component {...pageProps} />
                </ApiProvider>
            </Container>
        );
    }
}

Services/Api.js

import fetch from 'unfetch'

function Api (config)
{
    const apiUrl = config.endpoint;

    async function request (url) {
        return fetch(apiUrl + '/' + url);
    };

    this.decode = async function (code) {
        const res = request('/decode?code=' + code);
        const json = await res.json();
        return json;
    }

    return this;
}

export default Api;

Providers/ApiProvider.js

import React, { Component } from 'react';
import Api from '../Services/Api';

const defaultStore = null;

class ApiProvider extends React.Component
{
    state = {
        api: null
    };

    constructor (props) {
        super(props);

        this.state.api = new Api({ endpoint: props.endpoint });
    }

    render () {
        return (
            <ApiContext.Provider value={this.state.api}>
                {this.props.children}
            </ApiContext.Provider>
        );
    }
}

export const ApiContext = React.createContext(defaultStore);
export default ApiProvider;
export const ApiConsumer = ApiContext.Consumer;
export function withApi(Component) {
    return function withApiHoc(props) {
        return (
            <ApiConsumer>{ context => <Component {...props} api={context} /> }</ApiConsumer>
        )
    }
};

pages/code.js

import React, { Component } from 'react';
import Link from 'next/link';
import { withApi } from '../Providers/ApiProvider';

class Code extends React.Component
{
    static async getInitialProps ({ query, ctx }) {
        const decodedResponse = this.props.api.decode(query.code); // Cannot read property 'api' of undefined

        return {
            code: query.code,
            decoded: decodedResponse
        };
    }

    render () {
        return (
            <div>
                [...]
            </div>
        );
    }
}

let hocCode = withApi(Code);
hocCode.getInitialProps = Code.getInitialProps;
export default hocCode;

问题是我无法访问使用的上下文。我可以直接在我的 getInitialProps 中进行 fetch 调用,但是我想通过使用一个小函数来抽象它,该函数也采用可配置的 URL.

我做错了什么?

您无法在 static 方法 getInitialProps 中访问您的提供者的实例,它是在生成 React 树之前调用的(当您的提供者是可用)。

我建议您将 API 的 Singelton 保存在 API 模块中,并在 getInitialProps 方法中使用它通过常规导入。

或者,您可以将它注入 _app getInitialProps 中的 componentPage,类似这样:

// _app.jsx
import api from './path/to/your/api.js';

export default class Webshop extends App {
    static async getInitialProps({ Component, router, ctx }) {
        let pageProps = {}
        ctx.api = api;

        if (Component.getInitialProps) {
            pageProps = await Component.getInitialProps(ctx)
        }

        return { pageProps }
    }

    render () {
        const { Component, pageProps } = this.props

        return (
            <Container>
                <Component {...pageProps} />
            </Container>
        );
    }
}

// PageComponent.jsx

import React, { Component } from 'react';

class Code extends React.Component
{
    static async getInitialProps ({ query, ctx }) {
        const decodedResponse = ctx.api.decode(query.code); // Cannot read property 'api' of undefined

        return {
            code: query.code,
            decoded: decodedResponse
        };
    }

    render () {
        return (
            <div>
                [...]
            </div>
        );
    }
}

export default Code;

你觉得有意义吗?