Reactjs 反应挂钩:在切换模式下重新渲染过多
我正在尝试改进交换机主题代码,但出现以下错误: 错误:重新渲染过多。React将渲染数量限制为 防止无限循环 我的代码:Reactjs 反应挂钩:在切换模式下重新渲染过多,reactjs,Reactjs,我正在尝试改进交换机主题代码,但出现以下错误: 错误:重新渲染过多。React将渲染数量限制为 防止无限循环 我的代码: export default function App() { const theme = useTheme(); return ( <ThemeProvider theme={theme}> <GlobalStyle /> <div className="App"> <but
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>
);
}
我还想知道如何获得在我的setTheme
更改中发送的内容
onClick={theme.setTheme(
theme.type === 'dark' ? { type: 'light' } : { type: 'dark' },
)}
到
在代码中,在渲染期间立即执行setTheme,这会导致另一次渲染和递归无休止的渲染,该渲染会被react停止。onClick prop需要一个函数作为值,该函数将在单击期间执行 你好,非常感谢,你觉得代码好吗?你能告诉我我能不能给你看些东西吗?
onClick={theme.setTheme(
theme.type === 'dark' ? { type: 'light' } : { type: 'dark' },
)}
onClick={() => theme.setTheme(theme.type === 'dark' ? { type: 'light' } : { type: 'dark' })}