v6
路由跳转
- - 区别是`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>
</>
);
}
import { useNavigate, redirect } from "react-router-dom";
export default function Xxx() {
const navigate = useNavigate();
const go = () => {
redirect('/xxx')
};
return (
<>
<button onClick={go}>xxx</button>
</>
);
}
路由参数
参数格式:`/xxx?key=value&key=value`
<Link to="/message?name=jack">Message</Link>
import { useLocation } from "react-router-dom";
const location = useLocation();
console.log(location.search);
{
path: "message/:id",
element: <MessageDetail />,
},
<Link to="/message/123">MessageDetail</Link>
import { useParams } from "react-router-dom";
const params = useParams();
console.log(params);
import { useNavigate } from "react-router-dom";
const navigate = useNavigate();
navigate("/message", {
state: { content: "hello" },
});
import { useLocation } from "react-router-dom";
const location = useLocation();
console.log(location.state);
v5
history
{
key: 'ac3df4',
pathname: '/somewhere',
search: '?some=search-string',
hash: '#howdy',
state: {
[userDefined]: true
}
}

类组件中使用路由v5
https:
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))