带有useState和useEffect以及自定义钩子的难度

时间:2020-02-16 03:44:19

标签: reactjs

你好,我在使用自定义钩子时遇到了麻烦

正确渲染组件时,一切正常都会在存储中创建密钥,但是当我尝试单击switch主题时,我的setTheme总是变亮而不变暗

我不知道我在哪里错..:

代码:

export default function App() {
  const [theme, setTheme] = usePersistedState('theme', { type: 'light' });
  const toggleTheme = () => {
    setTheme(theme.type === 'light' ? { type: 'dark' } : { type: 'light' });
  };
  console.log(theme.type, 'aa');
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <div className="App">
        <button
          css={css`
            background: red;
            width: 100px;
            height: 50px;
            border-radius: 10px;
          `}
          onClick={toggleTheme}
        >
          a
        </button>
      </div>
    </ThemeProvider>
  );
}

自定义挂钩:

function usePersistedState(key, type) {
  console.log(key, type, 'xf');
  const [state, setState] = useState(() => {
    console.log('first');
    const storageValue = JSON.parse(localStorage.getItem(key));
    switch (storageValue) {
      case 'dark':
        return darkTheme;
      case 'light':
        return lightTheme;
      default:
        return lightTheme;
    }
  });

  useEffect(() => {
    const storageValue = JSON.parse(localStorage.getItem(key));
    if (storageValue !== state.type) {
      localStorage.setItem(key, JSON.stringify(state.type));
    }
  }, [key, state]);
  return [state, setState];
}

示例:

https://codesandbox.io/s/vigorous-goodall-x7x7d

gif:

tjs

1 个答案:

答案 0 :(得分:0)

App.js

setTheme(theme.type === "light" ? darkTheme : lightTheme);

将解决您的问题!