亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 history.push 重置 useState

使用 history.push 重置 useState

神不在的星期二 2021-07-06 13:57:28
在我的表格中,我執行以下操作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>我正在尋找一種解決方案來在登錄所有頁面后保持 isAuthenticated 狀態,即使在單擊另一個鏈接或調用 history.push 之后
查看完整描述

2 回答

?
忽然笑

TA貢獻1806條經驗 獲得超5個贊

究其原因isAuthenticated返回true時,你的個人資料頁上的第一個土地,但恢復到false時瀏覽到另一個頁面只能是該AuthProvider組件,當你點擊一個鏈接和狀態得到重新初始化被意外重新渲染。

您是否使用該<Link>組件進行鏈接?如果沒有,當導航到另一個頁面時,整個應用程序將被重新渲染并且狀態不會持續。


查看完整回答
反對 回復 2021-07-15
?
HUWWW

TA貢獻1874條經驗 獲得超12個贊

您的狀態正在重置,因為它在層次結構中位于 Router 之下。


<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>


查看完整回答
反對 回復 2021-07-15
  • 2 回答
  • 0 關注
  • 502 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號