简体   繁体   中英

React Hooks: Too many re-renders on switch mode

I'm trying to improve my switch theme code but I have the following error:

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

My code:

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>
  );
}

My hook:

   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);
      }
    },
  };
}

I would also like to know how I could get what was sent on my setTheme .

Change

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

To

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

In your code, you are immediately executing setTheme during render and it is causing another render and recursively endless rendering, which is stopped by react. onClick prop expects a function as the value, that function will be executed during click.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM