如何解决在SPA中使用React Router处理历史记录,包括按下浏览器后退按钮?
我正试图找到一个相关的问题,但是我没有。
在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();
}
在here中的回答
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。