react路由

53 阅读1分钟

v6

路由跳转

// 声明式导航 `Link` 和 `NavLink`
-   -   区别是`NavLink`激活时默认会有一个类名`active`
    -   如果希望跳转的链接高亮,用`NavLink`
import { Link, NavLink } from "react-router-dom";
export default function Xxx() {
  return (
    <>
      <Link to="/message">Message</Link>
      <NavLink to="/about">About</NavLink>
    </>
  );
}    
// 编程式导航 `useNavigate` 和 `redirect`
import { useNavigate, redirect } from "react-router-dom";
export default function Xxx() {
  const navigate = useNavigate();
  const go = () => {
    // navigate("/xxx"); // 添加 /xxx 浏览器历史记录(push)
    // navigate("/xxx", { replace: true }); // 替换 /xxx 浏览器历史记录(replace)
    // navigate(-1); // 回退一个浏览器历史记录
    // navigate(1); // 前进一个浏览器历史记录
    redirect('/xxx') // 替换 /xxx 浏览器历史记录(replace, 建议使用 redirect)
  };
  return (
    <>
      <button onClick={go}>xxx</button>
    </>
  );
}

路由参数

// query
参数格式:`/xxx?key=value&key=value`
// 1. 传递参数
<Link to="/message?name=jack">Message</Link>
// 2. 接受使用
import { useLocation } from "react-router-dom";
const location = useLocation();
console.log(location.search); // ?name=jack
// params
{
  path: "message/:id",
  element: <MessageDetail />,
},
// 2. 传递参数
<Link to="/message/123">MessageDetail</Link>
// 3. 接受使用
import { useParams } from "react-router-dom";
const params = useParams();
console.log(params); // { id: 123 }
// state 地址栏不可见
// 1. 传递参数
import { useNavigate } from "react-router-dom";
const navigate = useNavigate();
navigate("/message", {
  state: { content: "hello" },
});
// 2. 接受使用
import { useLocation } from "react-router-dom";
const location = useLocation();
console.log(location.state); // { content: "hello" }

v5

history

// history.push
{
    key: 'ac3df4', // not with HashHistory!
    pathname: '/somewhere',
    search: '?some=search-string',
    hash: '#howdy',
    state: {
     [userDefined]: true
    }
} 
// history.location获取参数的方法
// history 对象是可变的,所以我们不推荐从history.location 中获取 location,推荐从 props 中获取。这可以确保您对React的假设在生命周期挂钩中是正确的。例如:

image.png

类组件中使用路由v5

// 完整博客地址
https://blog.csdn.net/weixin_43778556/article/details/124018110
//  传递state参数并实现跳转
this.props.history.push('/state',{ id:item.id, title:item.title, content:item.content, })
// 接受参数
const {search} = this.props.location 
const {id,title} = qs.parse(search.slice(1))