路由跳转功能由React Router提供,需要先理解history,history是为React Router提供核心功能的包,能轻松地在客户端为项目添加基于location的导航,这种功能对于单页应用至关重要。
安装依赖:
npm install --save history
存在三类history,分别是browser,hash,与 memory。history包提供每种history的创建方法。
1.首先定义history:
无论创建哪种history,最终都会得到一个几乎拥有相同属性与方法的对象。
import { createMemoryHistory as createHistory } from "history";
export const history = createHistory();
// import { createBrowserHistory } from 'history';
//export const history = createBrowserHistory();
//import { useHistory } from 'react-router-dom';
//export const history = useHistory();
2.路由跳转与传参:
history.push('/hierarchy', {name:'sunny'});
还可以传递箭头函数做为参数:
history.push('/hierarchy', {
name: params.value.items.length > 0 ? params.value.items[0].data.name : "NULL",
hellofunction: ()=>{console.log("hello world!!!")}
});
3.获取参数:
路由跳转后,在目标组件中获取参数:
const Hierarchy = React.memo((props) => {
console.log(props.location.state.name);
//调用传递的函数参数
props.location.state.hellofunction();
}
其中用到了location对象,什么是location?
history对象中最重要的属性就是location,location对象反映了当前应用所在的"位置"。其包含了pathname,state(参数), search,hash这种由'URL'派生出的属性。
此外,每一个location都拥有一个与之关联且独一无二的key。'key'用于特定location的识别,向特定location存储数据。
最后,location可以拥有与之相关的状态。这是一些固定的数据,并且不存在于URL之中。