簡體   English   中英

useState正在使用history.push重置

[英]useState being reset with history.push

在我的表格中,我執行以下操作

import useReactRouter from 'use-react-router';

const { history } = useReactRouter();
onSubmit={async (values, { setSubmitting }) => {
  setSubmitting(true);
  fetch('/register', {
    method: 'POST',
    body: JSON.stringify(values),
    headers: {
      'Content-Type': 'application/json'
    }
  })
    .then(res => res.json())
    .then(async response => {
      setSubmitting(false);
      if (!response.success) return showAlert();
      await login();
      history.push('/profile');
    })

登錄執行此操作:

export const AuthContext = createContext<any>(null);

const AuthProvider = ({ children }: ProviderProps): JSX.Element => {
  const [auth, setAuth] = useState({
    isAuthenticated: false,
    user: null
  });

  const login = () => {
    fetch('/me')
      .then(res => res.json())
      .then(response => {
        if (response) setAuth({ isAuthenticated: true, user: response });
      });
  };

  const logout = () => {
    fetch('/logout').then(() =>
      setAuth({ isAuthenticated: false, user: null })
    );
  };

  return (
    <AuthContext.Provider
      value={{
        state: {
          auth
        },
        actions: {
          login,
          logout
        }
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

注冊后,`isAuthenticated在下面的代碼中返回true,但是導航到另一個頁面后,它再次返回false,這可能是什么問題?

const PrivateRoute = (props: PrivateRouteProps) => {
  const { component: Component, ...rest } = props;

  const {
    state: {
      auth: { isAuthenticated }
    }
  } = useContext(AuthContext);

  console.log(isAuthenticated);
<Router>
  <div>
    <AuthProvider>
      <Header />

      <Route exact path="/" component={Home} />
      <MuiPickersUtilsProvider utils={LocalizedUtils} locale={nlLocale}>
        <Route exact path="/register" component={Register} />
      </MuiPickersUtilsProvider>
      <PrivateRoute exact path="/profile" component={Profile} />
    </AuthProvider>
  </div>
</Router>

我正在尋找一種解決方案,即使在單擊另一個鏈接或調用history.push之后,也可以通過所有頁面登錄后保持isAuthenticated狀態。

isAuthenticated的原因true當您首次進入“個人資料”頁面時返回true ,但在導航到另一個頁面時又返回false ,這可能僅是當您單擊鏈接並狀態被初始化時, AuthProvider組件意外地重新呈現。

您是否使用<Link>組件進行鏈接? 如果不是,則導航到另一個頁面時,整個應用將被重新渲染,並且狀態不會持久。

您的狀態正在重置,因為它在層次結構中的路由器下方。

<AuthProvider>
<Router>
  <div>

      <Header />

      <Route exact path="/" component={Home} />
      <MuiPickersUtilsProvider utils={LocalizedUtils} locale={nlLocale}>
        <Route exact path="/register" component={Register} />
      </MuiPickersUtilsProvider>
      <PrivateRoute exact path="/profile" component={Profile} />

  </div>
</Router>
</AuthProvider>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM