在Back Button Click (REACTJS)上执行代码



下面的代码是执行当我浏览一个页面到另一个页面为例。当我单击类别页面列表中的产品时,下面的代码将设置一个会话存储键,该键将具有类别页面的位置(滚动了多少页)。

因此,当产品页面打开时,它将其密钥保存在会话&如果再次访问同一类别页面,则恢复页面位置。

我正试图使此代码仅保存一个会话密钥&删除先前保存的会话密钥,无论用户在网站上单击哪个页面(即类别页面,产品页面)。

CategoryPage.js

const [scrollPosition, setScrollPosition] = React.useState('');
React.useEffect(() => {
var pathName = document.location.pathname.substr(1);
if (window) {
window.onscroll = function (e) {
setScrollPosition(window.scrollY);
if(scrollPosition != 0){
sessionStorage.setItem("scrollPosition_"+pathName, scrollPosition);
}
};
}
}, [scrollPosition]);
React.useEffect(() => {
var pathName = document.location.pathname.substr(1);
if (window && sessionStorage.getItem("scrollPosition_"+pathName)) {
$(window).scrollTop(sessionStorage.getItem('scrollPosition_'+ pathName));
console.log('position_set to = ' + sessionStorage.getItem('scrollPosition_'+ pathName));
}
}, []);

对于删除之前的会话密钥有什么想法吗?

如果你在react中使用redux,你可以通过发送包含用户是否在产品页面上的信息的动作来跟踪位置。

像这样:

如果你有一些像

这样的路线
/category/house/3213124(product_id)
/category/garden/dsfsdfs(product_id)

在你的路由器中,你可以这样写:

/category/house/{id}
/category/garden/{id}

那么你可以使用:

let { id } = useParams();
if(id !== undefined || ""){
dispatch(userIsOnProductPageAction(true))
}

当用户点击后退按钮使用选择器对于reducer,您的信息是产品页面上的用户…如果为真执行代码,如果为假不执行任何操作.

在执行代码之后,你也可以调度userIsOnProductPageAction(false)

如果您不使用redux,您可以应用相同的逻辑,但问题是,您必须保持状态wasUserOnPage,并以某种方式在类别页面上访问它。

因为我不知道你的React应用看起来如何,所以我不能告诉你如何实现它。如果产品是子元素,而类别是父元素,你可以通过props发送这些信息。

编辑:它应该看起来像这样

class main extends React.Component {
constructor(props) {
super(props)
this.handler = this.handler.bind(this)
}
handler() {
this.setState({
wasOnProductPage:false
})
}
render() {
return <Category handler = {this.handler} props={this.props.wasOnProductPage} />
<Product handler = {this.handler} />
}
}
class Category extends React.Component {
render() {
if(props){
do code for viewport
then acitave this.props.handler and set it to false
}
}
}
class Product extends React.Component {
render() {
return <BackButton onClick = {this.props.handler(true)}/ >
}
}

我的理解是在加载页面时,您要:

  1. 如果该页是最后一次访问的页面:加载其保存位置
  2. Else:删除最后保存的位置并在滚动时保存。

那么看起来你需要保存一些带有你保存/加载位置的页面ID。这个唯一标识符可以是URL。

然后,您可以使用类似版本的代码:

const [scrollPosition, setScrollPosition] = React.useState('');
const getPathname = () => document.location.pathname.substr(1);
React.useEffect(() => {
if (window) {
window.onscroll = function (e) {
setScrollPosition(window.scrollY);
if (scrollPosition != 0) {
const savedPosition = { position: scrollPosition, pathName: getPathname() };
sessionStorage.setItem('scrollPosition', JSON.stringify(savedPosition));
}
};
}
}, [scrollPosition]);
React.useEffect(() => {
const lastSavedPosition = JSON.parse(sessionStorage.getItem('scrollPosition'));
if (window && lastSavedPosition && getPathname() === lastSavedPosition.pathName) {
$(window).scrollTop(lastSavedPosition.position);
console.log(`position_set to = ${lastSavedPosition.position}`);
}
}, []);

最新更新