基本组件 (Basic Components)
React Router 提供三种类型组件,分别是路由组件(router components),路由匹配组件(route matching components),以及导航组件(navigation components).
你使用以上的任何一个组件都必须要引入一个名为 react-router-dom 的文件
import { BrowserRouter, Route, Link } from 'react-router-dom'
2.1 路由 (Routers)
任何一个核心路由APP(REACT ROUTER APPLICATION)都必须为一个路由组件。对于web工程,react-router-dom 文件提供了
import { BrowserRouter } from 'react-router-dom'
ReactDOM.render((
), holder)
2.2 路由匹配(Route Matching)
我们提供了两种路由匹配组件,它们分别是:
import { Route, Switch } from 'react-router-dom'
路由匹配通过比较
// when location = { pathname: '/about' }
// renders
// renders null
// renders
你可以在任何你想要根据位置渲染的内容中去包含
当然
{/* when none of the above match, will be rendered */}
2.3 路由渲染参数
你可以有三个参数来选择你该如何渲染给出的
documentation来了解以上三个参数的更多信息,但是在这里, 我们将主要讲 component 和 render 方法,因为他们是两个最主要的方法,也是最常用的。
component 作用于你想要渲染的已经存在的组件(可以是 react.component ,也可以是无状态组件(pure function))。render 方法提供一个内部函数,当你想要对将被渲染的组件
传入内部变量的时候,你需要使用这个方法。 你不应该对component方法传入内部变量,因为component会有两个多余的方法 unmounts / remounts。
const Home = () => Home
const App = () => {
const someVariable = true;
return (
{/* these are good */}
}
/>
{/* do not do this */}
}
/>
)
}
2.4 导航
REACT ROUTER 提供组件,它在你的app内部创建一个链接(link),无论你在哪里渲染了
Home
// Home
// location = { pathname: '/react' }
React
// React
在任何时候,如果你想要强制导航,那么你可以渲染一个
Redirect to='/login'/>