[英]ReactJS: Save the location.state
I'm using React-Router to pass value from a page to another.我正在使用 React-Router 将值从一个页面传递到另一个页面。
I have two Page: PageA and PageB我有两个页面:PageA 和 PageB
In the PageA I have add a button to go in the PageB, passing in the state a value:在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>
In the PageB :在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}`);
}
}
Basically in the pageB I check if I come from the pageA and so if I have value props.location.state
I will use it to filter the data in the pageB using this value.基本上在 pageB 我检查我是否来自 pageA,所以如果我有值props.location.state
我将使用它来使用这个值过滤 pageB 中的数据。
If I don't have the value (so I go in the pageB from another place) I call the filter() that shows all the data without filter for value.如果我没有值(所以我从另一个地方在 pageB 中输入 go),我调用 filter() 来显示所有没有值过滤器的数据。
Now my problem is that: if i reload the page or click back from the other page I basically lose the props.location.state and therefore filter () is always called.现在我的问题是:如果我重新加载页面或从其他页面单击返回,我基本上会丢失 props.location.state,因此总是调用 filter ()。
How could I go about saving this value?我怎么能 go 关于保存这个值? So that if you refesh the page it stays with props.location.state因此,如果您刷新页面,它会保留在 props.location.state
You can use Window.localStorage for it.您可以为此使用 Window.localStorage。 See: https://www.w3schools.com/jsref/prop_win_localstorage.asp参见: https://www.w3schools.com/jsref/prop_win_localstorage.asp
You could use localStorage
or sessionStorage
.您可以使用localStorage
或sessionStorage
。
sessionStorage.setItem("urlState", state);
const urlState = sessionStorage.getItem("urlState");
Main difference between local and session storages, that session will live only while browser not closed本地和 session 存储之间的主要区别,即 session 仅在浏览器未关闭时存在
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.