React Hooks:切换模式下的重新渲染次数过多

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React Hooks:切换模式下的重新渲染次数过多相关的知识,希望对你有一定的参考价值。

您好,我正在尝试改善我的切换主题代码,但出现以下错误:

错误:重新渲染过多。 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>
  );

我的钩子:

import  darkTheme, lightTheme  from '../themes/index';

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 ) => _setTheme(theme),
  ;

而且我也想知道我如何获得在setTheme上发送的内容

答案

更改

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

收件人

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

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

以上是关于React Hooks:切换模式下的重新渲染次数过多的主要内容,如果未能解决你的问题,请参考以下文章