由于react-router-dom升級到6版本后,無法按照this.props.history.push()進(jìn)行編程式導(dǎo)航,此時props會提示是空值,v6文檔里把路由組件默認(rèn)接受的三個屬性給移除了,官網(wǎng)文檔里給出的解決方案是使用useNavigate()這個hook,但是hook只能存在于無狀態(tài)組件,無法用在類組件中,官方文檔里給出的類組件實現(xiàn)編程式導(dǎo)航的解決方案如下圖:

通過Navigate這個標(biāo)簽來實現(xiàn)路由跳轉(zhuǎn),但官方其實也不推薦,更推薦去使用hook。
實現(xiàn)方法
因為我是要實現(xiàn)登陸跳轉(zhuǎn)這個功能,不能像之前一樣利用history這個屬性去控制路由導(dǎo)航,所以官方文檔里給出的方法是設(shè)置一個state,然后在登陸成功時,改變這個state,在最后渲染組件時,通過state的狀態(tài)來控制路由的跳轉(zhuǎn),參考代碼如下:
export default class Login extends Component {
? state = {
? ? user: null,
? }
? render() {
? ? const { Header, Content, Footer } = Layout
? ? const NormalLoginForm = () => {
? ? ? const onFinish = async (values) => {
? ? ? ? //請求登陸
? ? ? ? const { username, password } = values
? ? ? ? const response = await reqLogin(username, password)
? ? ? ? const { status } = response.data
? ? ? ? if (status === 0) {
? ? ? ? ? message.success('登陸成功,歡迎' + response.data.user)
? ? ? ? ? this.setState({ user: response.data.user })
? ? ? ? } else {
? ? ? ? ? message.error(response.data.msg)
? ? ? ? }
? ? ? };
? ? return (
? ? ? <div>
? ? ? ? {this.state.user && (
? ? ? ? ? <Navigate to='/admin' replace='true' />
? ? ? ? )}
? ? ? ? <Layout>
? ? ? ? ? <Header>商品后臺管理系統(tǒng)</Header>
? ? ? ? ? <Content>
? ? ? ? ? ? <div className="login_container">
? ? ? ? ? ? ? <NormalLoginForm />
? ? ? ? ? ? </div>
? ? ? ? ? </Content>
? ? ? ? ? <Footer>©Copyright 2021 Ryan Wu</Footer>
? ? ? ? </Layout>
? ? ? </div>
? ? )
? }
}