繁体   English   中英

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

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

我需要在_app.js中使用 dispatch Context API 方法。 主要限制是我使用 React 钩子和上下文 API,因为_app.jsClass ,我不能在其中使用钩子。

我的代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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