React 钩子:在切换模式下重新渲染太多



我正在尝试改进我的开关主题代码,但我有以下错误:

错误:重新渲染过多。React 将渲染数量限制为 防止无限循环。

我的代码:

export default function App() {
const theme = useTheme();
return (
<ThemeProvider theme={theme}>
<GlobalStyle />
<div className="App">
<button
css={css`
background: red;
width: 100px;
height: 50px;
border-radius: 10px;
`}
onClick={theme.setTheme(
theme.type === 'dark' ? { type: 'light' } : { type: 'dark' },
)}
>
a
</button>
</div>
</ThemeProvider>
);
}

我的钩子:

export default function useTheme(defaultTheme = lightTheme) {
const [theme, _setTheme] = useState(getInitialTheme);
function getInitialTheme() {
const savedTheme = localStorage.getItem('theme');
return savedTheme === 'dark' ? darkTheme : defaultTheme;
}
useEffect(() => {
localStorage.setItem('theme', JSON.stringify(theme.type));
}, [theme]);
return {
...theme,
setTheme: ({ setTheme, ...theme }) => {
if (theme.type === 'dark') {
return _setTheme(darkTheme);
} else {
return _setTheme(lightTheme);
}
},
};
}

我还想知道如何获得setTheme上发送的内容。

更改

onClick={theme.setTheme(
theme.type === 'dark' ? { type: 'light' } : { type: 'dark' },
)}

onClick={() => theme.setTheme(theme.type === 'dark' ? { type: 'light' } : { type: 'dark' })}

在您的代码中,您在渲染期间立即执行 setTheme,它会导致另一个渲染和递归无休止的渲染,这被 react 停止。 onClick prop 需要一个函数作为值,该函数将在单击期间执行。

最新更新