为什么浏览器后退按钮返回包含上一URL的空白页面 [英] Why browser back button returns a blank page with the previous URL
本文介绍了为什么浏览器后退按钮返回包含上一URL的空白页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
按浏览器back button
为什么显示空白页面而不是我以前访问过的组件?仅将URL更改为以前的URL。
使用Reaction Router v5
这真让人沮丧,我怎么才能解决这个问题呢?
SignUp.js
render() {
return (
<div className='signUp-div'>
<Header />
<Router history={history}>
<div className='form-div'>
<Redirect to='/signup/mobile' /> // Default page
<Switch>
<Route exact path={'/signup/mobile'} component={MobileNum} />
<Route exact path={'/signup/idnumber'}>
<IdentNumber setPersonalID={this.props.setUserNumber} />
</Route>
<Route exact path={'/signup/password'}>
<CreatePass
setIfSignUp={this.props.setIfSignUp}
/>
</Route>
</Switch>
</div>
</Router>
</div>
);
}
IdentNumber.js
const IdentNumber = ({setPersonalID}) => {
const handleCheckID = () => {
history.push('/signup/password');
}
return (
<div className='form-div'>
<button
onChange={(event) => onChangeHandler(event)}
> Page password</button>
</div>
);
};
export default IdentNumber;
我的解释正确吗?
谢谢
推荐答案
从代码沙箱链接中,我观察到一些可能导致此问题的情况。
从import { Router } from "react-router-dom";
更新导入
至
import { BrowserRouter as Router } from "react-router-dom";
<BrowserRouter>
使用HTML5历史API(push State、replaceState和popstate事件)使您的UI与URL保持同步。
路线将保持不变。您正在使用act-route-dom v5.2.0,您可以使用useHistory
来获取历史记录对象。useHistory
简化了使组件具有路由感知功能的过程。
使用我的更改:https://codesandbox.io/s/suspicious-pine-5uwoq
当Switch
括在Switch
中并放在结尾时,除默认";/";之外的所有路由都不需要exact
密钥。但是exact
与/signup/mobile
和/signup/*
匹配相同。Switch
仅呈现一条路由,且先匹配的路由。
如果您希望自己处理后退按钮事件,请按照下面的示例操作。
在功能组件中,我们可以通过侦听历史记录对象来处理后退按钮的按下。
import { useHistory } from 'react-router-dom';
const Test = () => {
const history = useHistory();
useEffect(() => {
return () => {
if (history.action === "POP") {
}
};
}, [history])
}
收听useEffect
中的历史记录,了解组件是否已卸载。history.listen
让我们收听对历史记录的更改。
示例:
import { useHistory } from 'react-router-dom';
const Test = () => {
const history = useHistory();
useEffect(() => {
return history.listen(location => {
if (history.action === 'POP') {
}
})
}, [])
}
react-router-dom
现在有Prompt
,
import { Prompt } from "react-router-dom";
<Prompt
message={(location, action) => {
if (action === 'POP') {
// back button pressed
}
return location.pathname.startsWith("/test")
? true
: `Are you sure you want to go to ${location.pathname}?`
}}
/>
这篇关于为什么浏览器后退按钮返回包含上一URL的空白页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文