在SPA中使用React Router来处理历史记录,包括按下浏览器返回按钮



我试图找到一个相关的问题SO,但一直未能找到。

在SPA中,单击浏览器的后退按钮不会将用户带到您应用程序的上一个视图,而是会将您带到您以前访问过的任何网站。

我试过做下面这样的事情:

import React from 'react';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';
import styled from 'styled-components';
const Part0 = ({ history }) => {
React.useEffect(() => {
return () => {
if (history?.action === 'POP') {
console.log('pop0');
history.goBack();
}
};
}, []);
return <ComponentContainer>part0</ComponentContainer>;
};
const Part1 = ({ history }) => {
React.useEffect(() => {
return () => {
if (history?.action === 'POP') {
console.log('pop1');
history.goBack();
}
};
}, []);
return <ComponentContainer>part1</ComponentContainer>;
};
export default function Component() {
const [page, setPage] = React.useState(0);
const history = useHistory();
const dispatch = useDispatch()
const handleBack = React.useCallback(() => {
history.goBack();
}, []);
const handleForward = React.useCallback(() => {
history.push('');
setPage(page + 1);
}, [page]);
return (
<Main>
<ContentContainer>
{page === 0 && <Part0 history={history} />}
{page === 1 && <Part1 history={history} />}
<ButtonContainer>
<Button onClick={handleBack}>back</Button>
<Button onClick={handleForward}>forward</Button>
</ButtonContainer>
</ContentContainer>
</Main>
);
}
const Main = styled.div`
display: flex;
align-items: center;
justify-content: center;
`;
const ContentContainer = styled.div`
height: 20vh;
`;
const ButtonContainer = styled.div`
display: flex;
justifyContent: space-between;
alignItems: flex-end;
height: 100%;
width: 25vw;
`
const Button = styled.div`
width: 8rem;
cursor: pointer;
height: 3rem;
border: 1px solid gray;
display: flex;
justify-content: center;
align-items: center;
border-radius: 0.5rem;
transition: 0.5s;
&:hover {
background-color: #f1f1f1;
}
`;
const ComponentContainer = styled.div`
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
`;

当用户决定向前移动时,相关部分是history.push('');,而当用户决定单击浏览器的后退按钮时,则是history.goBack()

不幸的是,这没有奏效。有可能用React处理用户在SPA中点击浏览器的后退按钮吗?

要回答您的问题,您可以拦截返回按钮事件,如下所示:

componentDidMount() {
this.backListener = browserHistory.listen(location => {
if (location.action === "POP") {
// Do your stuff
}
});
}
componentWillUnmount() {
super.componentWillUnmount();
// Unbind listener
this.backListener();
}

正如在这里回答的那样

相关内容

  • 没有找到相关文章

最新更新