API _app.js class 组件 Next.js 中的上下文 API 调度(消费者)

Context API dispatch (consumer) in _app.js class component Next.js

我需要在 _app.js 中使用 dispatch Context API 方法。 主要限制是我将 React hooks 与 Context API 一起使用,因为 _app.jsClass,我不能在其中使用 hooks。

我的代码:

// store.js

import React, { createContext, useContext, useReducer } from "react";
import mainReducer from "../store/reducers";

const AppStateContext = createContext();
const AppDispatchContext = createContext();
const initialState = {
    filters: {
        diet: {
            selected: []
        }
    }
};

const useAppState = () => useContext(AppStateContext);
const useAppDispatch = () => useContext(AppDispatchContext);
const useApp = () => [useAppState(), useAppDispatch()];

const AppProvider = ({ children }) => {
    const [state, dispatch] = useReducer(mainReducer, initialState);

    return (
        <AppStateContext.Provider value={state}>
            <AppDispatchContext.Provider value={dispatch}>
                {children}
            </AppDispatchContext.Provider>
        </AppStateContext.Provider>
    );
};

export { AppProvider, useAppState, useAppDispatch, useApp };

// _app.js
import App from "next/app";
import React from "react";
import { AppProvider } from "../store";

class MyApp extends App {

    componentDidMount() {

        /***********************************/
        // HERE I WOULD LIKE TO USE DISPATCH
        /***********************************/

    }

    render() {
        const { Component, router, pageProps } = this.props;
        return (
                <AppProvider>
                        <Component {...pageProps} />
                </AppProvider>
        );
    }
}

export default MyApp;

如果你真的想使用钩子,那么只需像这样在 _app.js 周围放置一个包装器:

import React from 'react'
import App from 'next/app'

function MyComponent({ children }) {
  // You can use hooks here
  return <>{children}</>
}

class MyApp extends App {
  render() {
    const { Component, pageProps } = this.props
    return (
      <MyComponent>
        <Component {...pageProps} />
      </MyComponent>
    )
  }
}

export default MyApp