React context API超过了最大更新深度

时间:2020-10-03 08:56:47

标签: reactjs react-context

我的项目中有三个主题,我想使用React Context API处理主题切换过程,但是出现了“超出最大更新深度”错误。我该如何处理?

这是我的数据层:

[Name]

这是我的减速器:

import React from "react";

// Data Layer
export const StateContext = React.createContext();

// Provider
export const StateProvider = ({ reducer, initialState, children }) => (
  <StateContext.Provider value={React.useReducer(reducer, initialState)}>
     {children}
  </StateContext.Provider>
);

export const useStateValue = () => React.useContext(StateContext);

这是index.js:

export const initialState = {
  theme: "",
};

export const reducer = (state, action) => {
  if (action.type === "SET_THEME") {
    return {
            ...state,
            theme: action.userTheme,
    };
    } else {
            return state;
    }
 };

用户在导航栏组件中切换主题,这是我的导航栏:

import { StateProvider } from "./context/StateProvider";
import { initialState, reducer } from "./context/reducer";

ReactDOM.render(
  <React.StrictMode>
    <StateProvider initialState={initialState} reducer={reducer}>
      <App />
    </StateProvider>
 </React.StrictMode>,
 document.getElementById("root")
 );

最后是App.js:

import { useStateValue } from "../context/StateProvider";

export const Nav = () => {
   const [state, dispatch] = useStateValue();

   const setTheme = (theme) => {
      dispatch({
        type: "SET_THEME",
        userTheme: theme,
      });
    };

    return (
       <>
          <div onClick={setTheme("theme-orange")}>
             <a id="orange" href="javascript:void(0)">
               orange
             </a>
          </div>

          <div onClick={setTheme("theme-green")}>
             <a id="green" href="javascript:void(0)">
               green
             </a>
          </div>

          <div onClick={setTheme("theme-blue")}>
             <a id="blue" href="javascript:void(0)">
               blue
             </a>
          </div>
       </>
    )
}

1 个答案:

答案 0 :(得分:2)

您正在Nav组件上的渲染上执行setState。试试:

<div onClick={() => setTheme("theme-orange")}>
  <a id="orange" href="javascript:void(0)">
    orange
  </a>
</div>