[英]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
您可以使用localStorage
或sessionStorage
。
sessionStorage.setItem("urlState", state);
const urlState = sessionStorage.getItem("urlState");
本地和 session 存储之间的主要区别,即 session 仅在浏览器未关闭时存在
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.