Appearance
跑通路由
本节目标:理解“跑通路由”的核心思路,并能把它用于实际开发或面试表达。
说明:原 OneNote 中有图片引用,但图片未包含在导出目录中;本页保留了可用的文字与代码内容。
createBrowserHistorycreateHashHistory.js
npm i react-router-dom @types/react-router-dom path-to-regexp -S
当你安装了react-router-dom 适用于浏览器端的库,会自动安装以下库:
react-router才是真正的路由库跨平台,可以应用浏览器canvasvr;history底层实现模拟历史对象的库 内部写了二套,一套是使用hash,一套是使用window.history;
src\index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import { HashRouter as Router, Route } from './react-router-dom';
import Home from './components/Home';
import User from './components/User';
import Profile from './components/Profile';
debugger
ReactDOM.render(
<Router>
<Route path="/" exact={true} component={Home} />
<Route path="/user" component={User} />
<Route path="/profile" component={Profile} />
</Router>,
document.getElementById('root')
);
src\components\Home.tsx
import React from "react";
export default class Home extends React.Component {
render() {
console.log(this.props);
return <div>Home</div>
}
}
User.tsx
import React from "react";
export default class User extends React.Component {
render() {
console.log(this.props);
return <div>User</div>
}
}
src\components\Profile.tsx
import React from "react";
export default class Profile extends React.Component {
render() {
return <div>Profile</div>
}
}
{
history: H.History;
location: H.Location < S >;
match: match < Params >;
staticContext ?: C;
}
export interface Location<S = LocationState> {
pathname: Pathname;
state: S;
}
export interface match<Params extends { [K in keyof Params]?: string } = {}> {
params: Params;
isExact: boolean;
path: string;
url: string;
}以上打印结果:
