处理 React 中的 localStorage 更改以重新渲染组件

the*_*tud 10 javascript reactjs

我的应用程序调用第 3 方 api/函数来更改 localStorage 变量isUserLoggedIn。

是否可以在 localStorage 更改时重新渲染组件?我的应用程序根据以下值进行渲染localStorage.getItem('isUserLoggedIn')

<div>
        {
        localStorage.getItem('isUserLoggedIn') ?
        <GlobalHeader
          uniqueid="GlobalHeader"            
          signoutclickhandler={this.signOutHandler}
        />
        :
        <GlobalHeader
          uniqueid="GlobalHeader"    
          signinclickhandler={this.signInHandler}
        />
        }
      </div>
Run Code Online (Sandbox Code Playgroud)

Adi*_*ler 1

我的情况是:

我有一个与后端一起使用的函数

function callApi() {
  try {

} catch() {
    clearToken(); // custom func for clearing tokens
   // here I need to throw out the user when token is cleared
}
}
Run Code Online (Sandbox Code Playgroud)

我想使用“useEffect”钩子来抛出

    export function App () {
       useEffect(() => {
         if (!tokenFromLocalStorage) {
            history.push('/login'); // react router history. url changing.
            // I could not do this in the callApi func, because it would be
           // neccessary to pass 'history' to the callApi as param on each calling
          }
        }, [tokenFromLocalStorage]);
     
    return (<div></div>)
    }
  
Run Code Online (Sandbox Code Playgroud)

但问题是useEffect 不会调用,因为本地存储更改不会重新呈现应用程序。

为了解决这个问题:

export function App () {
       useEffect(() => {
         if (!tokenFromLocalStorage) {
            history.push('/login');
          }
        }, [tokenFromLocalStorage]);

    return (<div></div>)
    }



function callApi() {
  try {
   ...
} catch() {
    clearToken();

    window.location.reload(); // throw out on the 'login' page if there are no tokens.
            // forced reload needed because changing local storage
            // does not rerender application
  }
}
Run Code Online (Sandbox Code Playgroud)

目前,useEffect 将起作用并将用户踢出。