简体   繁体   中英

How to keep the state even after refresh

I'm trying to pass the current state from one page to another and it works when I transferred it. However, the new problem is to keep the current state on the new page. Every time I refresh the page, the state is gone and keep getting an error says "cannot read property 'state' of undefined". I tried to use the useEffect from Hooks, but it still didn't work. Here's the step by step code:

My Product Page:

<Grid container direction="row" justify="center" alignItems="center">
  {currentSearch.map((productObj) => {
    // console.log(productObj);
    return (
      <ProductResult
        name={productObj.name}
        price={productObj.price}
        style={productObj.style}
        type={productObj.type}
        depth={productObj.depth}
        height={productObj.height}
        width={productObj.width}
      />
    );
  })}
</Grid>

Will be passed on to ProductResult component:

<Link
  to={{
    pathname: '/product/description',
    infoObj: {
      text: 'This is information passed on',
      state: {
        ...props,
      },
    },
  }}
>
  Product Description
</Link>

Then go to the product description:

const [loadInfo, setLoadInfoState] = useState('');
useEffect(() => {
  // loadDescrInfo();
  setLoadInfoState(props.location.infoObj.state);
}, []);
console.log(loadInfo);

Really appreciate any advice or help from y'all. Thank you

You need to save your state to localStorage or sessionStorage and when component mounts, pass the value from storage to your state. Read about localStorage: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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