ReactJS: Save the location.state



我使用React Router将值从一个页面传递到另一个页面。

我有两页:A页和B页

PageA中,我在PageB中添加了一个按钮,在状态中传递一个值:

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

页面B中:

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}`);
}
}

基本上,在页面B中,我检查我是否来自页面A,因此如果我有值props.location.state,我将使用它来使用该值过滤页面B中的数据。

如果我没有值(所以我从另一个地方进入pageB(,我会调用filter((,它显示所有没有值过滤器的数据。

现在我的问题是:如果我重新加载页面或从另一个页面单击返回我基本上失去了props.location.state,因此总是调用filter((。

我该如何保存这个值?这样,如果你重新刷新页面,它就会停留在props.location.state

您可以使用Window.localStorage。请参阅:https://www.w3schools.com/jsref/prop_win_localstorage.asp

您可以使用localStoragesessionStorage

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

本地存储和会话存储之间的主要区别是,只有当浏览器未关闭时,会话才会存在

最新更新