首先const navigate = useNavigate();
则可以使用navigate这个函数代替this.history.push、this.history.replace、this.history.gofoward、this.history.goback、this.history.go
1.注意:navigete默认history的是push模式,使用replace模式需要添加

{replace:true} //开启replace模式

2.注意:使用useNavigate()必须是在函数式组件中
一开始用在类式组件中,报错:

react-dom.development.js:14906 Uncaught Error: Invalid hook call.
Hooks can only be called inside of the body of a function component.
This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app

完整代码:
(以params接收参数为例)
src/pages/Home/Message:

import React, { Component } from 'react'
import { Link, Route, Routes, useParams, useNavigate } from 'react-router-dom'
import Detail from './Detail'

const state = {
    messageArr: [
        { id: '01', title: 'message1' },
        { id: '02', title: 'message2' },
        { id: '03', title: 'message3' },
    ]
}

const Message = () => {
    const { messageArr } = state
    const navigate = useNavigate();

    //push跳转 以params参数为例,navigate默认开启push模式
    const pushShow = (id, title) => {
        navigate(`/home/message/detail/${id}/${title}`)
    }

    //replace跳转 以params参数为例,开启replace:true
    const replaceShow = (id, title) => {
        navigate(`/home/message/detail/${id}/${title}`, { replace: true })
    }

    //前进
    const forward = () => {
        navigate(1)
    }
    //前进
    const back = () => {
        navigate(-1)
    }
    //go
    //前进
    const go = () => {
        navigate(2)
    }
    return (
        <div>
            <ul>
                {
                    messageArr.map((msgObj) => {
                        return (
                            <li key={msgObj.id}>
                                {/* 向路由组件传递params参数 */}
                                <Link to={`/home/message/detail/${msgObj.id}/${msgObj.title}`}>{msgObj.title}</Link>&nbsp;&nbsp;

                                  &nbsp;<button onClick={() => { pushShow(msgObj.id, msgObj.title) }}>push</button>
                                <button onClick={() => { replaceShow(msgObj.id, msgObj.title) }}>replace</button>
                            </li>
                        )
                    })
                }
            </ul>
            <hr />
            <Routes>
                {/* 声明接收params参数 */}
                <Route path="/detail/:id/:title" element={<Detail />} />
            </Routes>

            <button onClick={forward}>前进</button>
            <button onClick={back}>后退</button>
            <button onClick={go}>go</button>
        </div>
        
    )
}
export default Message



Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐