简体   繁体   中英

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

I need to use dispatch Context API methods in _app.js . The main limitation is that I use React hooks along with Context API, since _app.js is a Class , I can't use hooks within it.

My code:

// 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;

If you really want to use hooks, then just put a wrapper around _app.js like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM