[英]While using react-router 5 with redux 7 react-router <Link> is not resetting state after going to new route
[英]state value getting lost even after storing it in localstorage [React/React-router]
我向 api 提出請求,作為回報,我得到“你好”。 我將此 hello 存儲在 test_text變量中,然后作為回報,如果未設置 test_text,我希望將用戶重定向到另一個 url。 否則我想展示一個組件。
在我刷新頁面之前,此代碼工作正常。
刷新頁面后,由於某種原因, test_text 被設置回“”(空字符串) ,因此將我重定向回“/”url。 這很令人困惑,因為使用 UseEffect,我將“hello”存儲在 localstorage 中,而使用另一個 useEffect 我試圖從 localstorage 獲取“hello”文本。 這是代碼。 請幫我。
import {React,useState,useEffect} from 'react';
import { BrowserRouter as Router, Switch, Route, Redirect } from 'react-router-dom';
import Landing from './components/landing/LandingIndex';
import Home from './components/home/HomeIndex';
function App() {
const [test_text, setText_text] = useState('');
useEffect(()=>{
const data = localStorage.getItem('data');
console.log(localStorage.getItem('data')); // hello
if(data){
setText_text(JSON.parse(data));
}
},[])
useEffect(() => {
fetch('/sessionDetails', {
method: 'POST',
cache: 'no-cache',
headers: {
'content_type': 'application/json',
},
body: JSON.stringify()
}).then(response => {
return response.json()
}).then(json => {
console.log(json.result_text) // hello
setText_text(json.result_text);
localStorage.setItem("data", JSON.stringify(json.result_text))
})
},[])
return (
<div className='App'>
<Router>
<Switch>
<Route path = '/' exact component = {Landing}/>
<Route exact path = '/home'>
{test_text === '' ? <Redirect to="/" /> : <Home />}
</Route>
</Switch>
</Router>
</div>
);
}
export default App;
在組件完成渲染后調用useEffect
:請參閱useEffect 做什么?
當您的組件完成第一次渲染時:
test_text
仍然等於其初始 state即''
。test_text === ''
,當 JSX 被渲染時使用<Redirect>
useEffect
來更新test_text
state偽代碼
在此示例中,檢查localStorage.getItem('data')
是否為falsy是有意義的。
false
,則使用<Redirect/>
組件<Home/>
組件。代碼
嘗試更改這行代碼:
{test_text === '' ? <Redirect to="/" /> : <Home />}
對此:
{!localStorage.getItem('data') ? <Redirect to="/" /> : <Home />}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.