简体   繁体   English

即使将 state 值存储在 localstorage [React/React-router] 中,它的值也会丢失

[英]state value getting lost even after storing it in localstorage [React/React-router]

I make a request to the api and in return I get "hello".我向 api 提出请求,作为回报,我得到“你好”。 I store this hello in a test_text variable and later in return I would want to redirect user to another url if test_text is not set.将此 hello 存储在 test_text变量中,然后作为回报,如果未设置 test_text,我希望将用户重定向到另一个 url。 Else I would want to present a component.否则我想展示一个组件。

This code is working properly UNTIL I refresh the page.在我刷新页面之前,此代码工作正常

After refreshing the page, for some reason, test_text is being set back to "" (empty string) which is therefore redirecting me back to "/" url.刷新页面后,由于某种原因, test_text 被设置回“”(空字符串) ,因此将我重定向回“/”url。 This is confusing because using UseEffect, I am storing "hello" in localstorage and using another useEffect I am trying to get the "hello" text from localstorage.这很令人困惑,因为使用 UseEffect,我将“hello”存储在 localstorage 中,而使用另一个 useEffect 我试图从 localstorage 获取“hello”文本。 Here's the code.这是代码。 Please help me.请帮我。

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 is called after the component has finished rendering: See What does useEffect do?在组件完成渲染调用useEffect :请参阅useEffect 做什么?

When your component finishes its first render:当您的组件完成第一次渲染时:

  • the test_text is still equal to its initial state ie '' . test_text仍然等于其初始 state''
  • since test_text === '' , the <Redirect> is used when the JSX is rendered由于test_text === '' ,当 JSX 被渲染时使用<Redirect>
  • after all the JSX has been rendered, the useEffect is called to update the test_text state渲染完所有 JSX 后,调用useEffect来更新test_text state

Pseudocode伪代码

In this example, it makes sense to check that localStorage.getItem('data') is falsy .在此示例中,检查localStorage.getItem('data')是否为falsy是有意义的。

  • if false , use the <Redirect/> component如果为false ,则使用<Redirect/>组件
  • else use the <Home/> component.否则使用<Home/>组件。

Code代码

Try changing this line of code:尝试更改这行代码:

{test_text === '' ? <Redirect to="/" /> : <Home />}

to this:对此:

{!localStorage.getItem('data') ? <Redirect to="/" /> : <Home />}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM