我的项目中有三个主题,我想使用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>
</>
)
}
答案 0 :(得分:2)
您正在Nav
组件上的渲染上执行setState。试试:
<div onClick={() => setTheme("theme-orange")}>
<a id="orange" href="javascript:void(0)">
orange
</a>
</div>