簡體   English   中英

React 不會刷新 LocalStorage 中的 state

[英]React doesn't refresh state in LocalStorage

你好嗎?

我正在使用 React 和 Cognito 托管 UI 進行概念驗證。 我在這里使用反應路由器 dom 有此代碼:

return (
      <div>
        <main>
          <Switch>
          < Route path='/' exact>
              {
              (localStorage.getItem('access_token') && localStorage.getItem('access_token')!=='undefined') ? history.replace('/home'): (
                <div>
                  <b>You are not logged in Igor, please log in using Google or User and Password. </b>
                  <b></b>
                  <a href="https://<MY_DOMAIN>.auth.us-east-1.amazoncognito.com/login?client_id=<MY_CLIENT_ID>&response_type=code&scope=aws.cognito.signin.user.admin+email+openid+phone+profile&redirect_uri=<MY_CLOUDFRONT_DISTRIBUTION_APEX>">Sign in</a>
                </div>
              )
              }
            </Route>
            <Route path='/calculator'>
              <Calculator/>
            </Route>
            <Route path='/home/'>
              <Welcome/>
            </Route>
            <Route path='/welcome/'>
              <RedirectPage/>
            </Route>
          </Switch>
        </main>
      </div>
    ); 

我使用 S3 作為 static 網站托管,這就是為什么我指向 S3 雲端分發頂點。 然后,在我的應用程序 function(App.js 文件中的 residex)中,我每次用戶訪問時都進行此驗證,以驗證這是否來自重定向,如果出現,我將 auth_code 交換為 JWT 令牌,這將是與 API 網關一起使用:

      const location = useLocation();
      const history = useHistory();
      let authCode = new URLSearchParams(location.search).get('code');
      console.log(authCode)

      if(authCode){
        fetch('https://<GATEWAY_ID>.execute-api.us-east-1.amazonaws.com/dev/auth',{
              method: 'POST',
              body: JSON.stringify(authCode),
              headers: {
                'Content-Type': 'application/json'
              }
            }).then((res)=>{return res.json()}).then(data=>{
              console.log('access token is:');
              console.log(data.result['access_token']);
              console.log('id token is:');
              console.log(data.result['id_token']);
              localStorage.setItem('access_token',data.result['access_token']);
              history.replace('/home')
            });
      }

問題是,在我使用谷歌或登錄名和密碼進行身份驗證后,我收到代碼,我在后端使用 lambda(在 /dev/auth 路由上,網關后面)在 cognito 上進行身份驗證,lambda 執行身份驗證好吧,但是我的前端頁面進入了一個循環,並且在打印 null 很多次之后(從 console.log(authCode) 行,我收到一個錯誤,告訴我在一個循環中)。 我是反應的新手,我做這個 POC 是為了理解這個概念並向客戶展示這個過程。

提前致謝。 我無法完整共享代碼,因為它們存儲在私人公司存儲庫中。

我的完整代碼:

import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Calculator from './pages/Calculator';
import Welcome from './pages/Welcome';
import {useHistory, useLocation} from 'react-router-dom';
import RedirectPage from './pages/Loading';

function App() {
      const location = useLocation();
      const history = useHistory();
      let authCode = new URLSearchParams(location.search).get('code');
      console.log(authCode)

      if(authCode){
        fetch('https://<GATEWAY_ID>.execute-api.us-east-1.amazonaws.com/dev/auth',{
              method: 'POST',
              body: JSON.stringify(authCode),
              headers: {
                'Content-Type': 'application/json'
              }
            }).then((res)=>{return res.json()}).then(data=>{
              console.log('access token is:');
              console.log(data.result['access_token']);
              console.log('id token is:');
              console.log(data.result['id_token']);
              localStorage.setItem('access_token',data.result['access_token']);
              history.replace('/home')
            });
      }
    
    return (
      <div>
        <main>
          <Switch>
          < Route path='/' exact>
              {
              (localStorage.getItem('access_token') && localStorage.getItem('access_token')!=='undefined') ? history.replace('/home'): (
                <div>
                  <b>You are not logged in Igor, please log in using Google or User and Password. </b>
                  <b></b>
                  <a href="<HOSTED_UI_COGNITO>">Sign in</a>
                </div>
              )
              }
            </Route>
            <Route path='/calculator'>
              <Calculator/>
            </Route>
            <Route path='/home/'>
              <Welcome/>
            </Route>
            <Route path='/welcome/'>
              <RedirectPage/>
            </Route>
          </Switch>
        </main>
      </div>
    ); 
}

export default App;

我可以看到您已經在功能組件中編寫了 api 調用代碼,我假設您只想點擊 api 一次以實現您可以在 useEffect 中編寫您的代碼

 useEffect(()=>{
    if(authCode){
        fetch('https://<GATEWAY_ID>.execute-api.us-east-1.amazonaws.com/dev/auth',{
              method: 'POST',
              body: JSON.stringify(authCode),
              headers: {
                'Content-Type': 'application/json'
              }
            }).then((res)=>{return res.json()}).then(data=>{
              console.log('access token is:');
              console.log(data.result['access_token']);
              console.log('id token is:');
              console.log(data.result['id_token']);
              localStorage.setItem('access_token',data.result['access_token']);
              history.replace('/home')
            });
      }
    
    },[])

暫無
暫無

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

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