【问题标题】:React Hooks: Too many re-renders on switch modeReact Hooks:切换模式下的重新渲染过多
【发布时间】:2020-02-16 23:02:15
【问题描述】:

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

错误:重新渲染过多。 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 发送的内容。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    改变

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

    到

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

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

    【讨论】:

    • 您好,非常感谢,您觉得代码好吗?你能告诉我是否可以展示一些东西吗?
    猜你喜欢
    • 1970-01-01
    • 2020-02-23
    • 2020-01-07
    • 1970-01-01
    • 2021-03-22
    • 2020-03-28
    • 1970-01-01
    • 2020-07-07
    • 2020-02-05
    相关资源
    最近更新 更多