簡體   English   中英

ReactJS:保存位置state

[英]ReactJS: Save the location.state

我正在使用 React-Router 將值從一個頁面傳遞到另一個頁面。

我有兩個頁面:PageA 和 PageB

PageA中,我在 PageB 中向 go 添加了一個按鈕,並在 state 中傳遞了一個值:

<Button tag={Link} to={{pathname: `/pageB`, state: `${value.id}`}} replace color="primary">
 <span className="d-none d-md-inline">PageB</span>
</Button>

PageB 中

  useEffect(() => {
    if(props.location.state){
      console.log("props.location.state ", props.location.state)
      filterWithValue(props.location.state)
    }
    else {
      filter();
    }

  }, [paginationState.activePage, paginationState.order, paginationState.sort]);

const dataFromValue= parameter => {
    const params = `id.equals=${parameter}`
    props.getDataFromValue(
      params,
      paginationState.activePage - 1,
      paginationState.itemsPerPage,
      `${paginationState.sort},${paginationState.order}`)
  }

  const filterWithValue= params => {
    dataFromValue(params)
    const endURL = `?page=${paginationState.activePage}&sort=${paginationState.sort},${paginationState.order}${params ? '&' : ''}id.equal=${params}`;
    if (props.location.search !== endURL) {
      props.history.push(`${props.location.pathname}${endURL}`);
    }
  }

基本上在 pageB 我檢查我是否來自 pageA,所以如果我有值props.location.state我將使用它來使用這個值過濾 pageB 中的數據。

如果我沒有值(所以我從另一個地方在 pageB 中輸入 go),我調用 filter() 來顯示所有沒有值過濾器的數據。

現在我的問題是:如果我重新加載頁面或從其他頁面單擊返回,我基本上會丟失 props.location.state,因此總是調用 filter ()。

我怎么能 go 關於保存這個值? 因此,如果您刷新頁面,它會保留在 props.location.state

您可以為此使用 Window.localStorage。 參見: https://www.w3schools.com/jsref/prop_win_localstorage.asp

您可以使用localStoragesessionStorage

sessionStorage.setItem("urlState", state);
const urlState = sessionStorage.getItem("urlState");

本地和 session 存儲之間的主要區別,即 session 僅在瀏覽器未關閉時存在

暫無
暫無

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

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