Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 反应挂钩:在切换模式下重新渲染过多_Reactjs - Fatal编程技术网

Reactjs 反应挂钩:在切换模式下重新渲染过多

Reactjs 反应挂钩:在切换模式下重新渲染过多,reactjs,Reactjs,我正在尝试改进交换机主题代码,但出现以下错误: 错误:重新渲染过多。React将渲染数量限制为 防止无限循环 我的代码: export default function App() { const theme = useTheme(); return ( <ThemeProvider theme={theme}> <GlobalStyle /> <div className="App"> <but

我正在尝试改进交换机主题代码,但出现以下错误:

错误:重新渲染过多。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>
  );
}
我还想知道如何获得在我的
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' })}