Home >Web Front-end >JS Tutorial >Detailed explanation of steps to use React-router v4
This time I will bring you a detailed explanation of the steps to use React-router v4. What are the precautions when using React-router v4? The following is a practical case, let’s take a look.
Perhaps the best way to learn react-router is to use react-router-dom v4 to write a multi-page react application. This react application will include login, registration, homepage, contact and other pages. But first let's take a look at the concept of react router v4 and how it differs from v3.
v4 is a rewrite of react router, so it has many differences from v3. The main ones are:
In react router v4, routing is no longer centralized. It becomes part of the application layout and UI.
The router used by the browser is in react-router-dom
. Therefore, when using it in the browser, you only need to import react-router-dom
.
New concepts BrowerRouter
and HashRouter
. They each serve different situations. See below for details.
No longer use {props.children}
to handle nested routes.
v4 routing is no longer exclusive by default and will have multiple matches. v3 is exclusive by default, and only one match will be used.
react-router-dom
is used in react-router for browsers. react-router
is divided into the following parts:
react-router is a common part for browsers and native applications.
react-router-dom is for browsers.
react-router-native is for native applications.
react-router
is the core part. react-router-dom
Provides customized components required for browser use. react-router-native
specifically provides the parts that need to be used in native mobile applications. Therefore, if you implement browser development in this example, you only need to install react-router-dom
.
As mentioned above, we use react to develop web applications, so we only need to install react-router-dom
.
npm install react-router-dom --save
BrowserRouter
, which is the implementation of the Router
interface. Make the page and browser history consistent. For example: window.location
.
HashRouter
is the same as above, except that it uses the hash part of the url, such as: window.location.hash
.
MemoryRouter
,
##NativeRouter, handle routing in react native.
Static<a href="http://www.php.cn/wiki/188.html" target="_blank">Router</a>, handles static routing, the same as v3.
and
can be used in the browser. If you are using a non-static site and want to handle various URLs, then you need to use
BrowserRouter. On the contrary, if your server only handles static URLs, use
HashRouter.
Route component.
Route component can use the following attributes:
path is successfully matched.
还有其他的一些属性,可以用来代替component
属性。
render属性,一个返回React组件的方法。传说中的rencer-prop就是从这里来的。
children属性,返回一个React组件的方法。只不过这个总是会绘制,即使没有匹配的路径的时候。
多数的时候是用component
属性就可以满足。但是,某些情况下你不得不使用render
或children
属性。
match
location
history
如:
使用组件:
<Route exact path="/" component={HomePage} />
使用render
属性实现内联绘制:
<Route path="/" render={()=><p>HomePage</p>} />
来看哥更复杂的:
const FadingRoute = ({ component, ...rest }) => ( <Route {...rest} render={(props) => ( <FadeIn> <componnet {...props} /> </FadeIn> )} /> ) <FadingRoute path="/cool" component={Something} />
使用children
:
<ul> <ListItemLink to="/somewhere" /> <LinkItemLink to="/somewhere-else" /> </ul> const ListItemLink = ({to, ...rest}) => ( <Route path={to} children={({math}) => ( <li className={match ? 'active' : ''}> <Link to={to} {...rest} /> </li> )} /> )
更多关于react-router v4如何匹配路径的内容,请移步这里。
通常情况下,我们都会在路径里添加参数。这样方便在不同的组件之间传递一些必要的数据。那么我们如何才能获取到这些传递的参数,并传递给组件中呢?我们只需要在路径的最后加上/:param
。如:
<Route path="/:param1" component={HomePage} /> const HomePage = ({match}) => ( <p> <h1> parameter => {match.params.param1} </p> );
一旦有路径可以匹配成功,那么就会穿件一个拥有如下属性的对象,并传入绘制的组件里:
url: 匹配的url。
path:就是path。
isExact:如果path
和当前的widnow.location
的path部分完全相同的话。
params:在URL里包含的参数。
Link
是react router v4特有的一个组件。是用来代替上一版的anchor link。使用Link
可以在React应用的不同页面之间跳转。与unclor会重新加载整个页面不同,Link
只会重新加载页面里和当前url可以匹配的部分。
Link
组件需要用到to
属性,这个属性的值就是react router要跳转到的地址。如:
import { Link } from 'react-router-dom'; const Nav = () => ( <Link to '/'>Home</Link> );
当被点击的时候,会跳转到路径:/
。
to
属性的值可以是一个字符串,也可以是一个location(pathname, hash, state和search)对象。比如:
<Link to{{ pathname: '/me', search: '?sort=asc', hash: '#hash', state: { fromHome: true } }} />
Link
也可以使用replace
属性,如果点击的话,那么history里的当前领会被replace。
NavLink
是Link
的一个子类,在Link组件的基础上增加了绘制组件的样式,比如:
<NavLink to="/me" activeStyle={{SomeStyle}} activeClassName="selected"> My Profile </NavLink>
现在我们用react router dom来实现第一个demo。
首先,引入必要的组件。比如:Route
和BrowserRouter
。
import { BrowserRouter, Route } from 'react-router-dom';
接下来,我们创建一些组件和一些Html标签。同时我们用react router v4里的Link
和NavLink
组件。
const BaseLayout = () => ( <p className="base"> <header> <p>React Router v4 Browser Example</p> <nav> <ul> <li><Link ="/">Home</Link></li> <li><Link ="/about">About</Link></li> <li><Link ="/me">Profile</Link></li> <li><Link ="/login">Login</Link></li> <li><Link ="/register">Register</Link></li> <li><Link ="/contact">Contact</Link></li> </ul> </nav> </header> <p className="container"> <Route path="/" exact component={HomePage} /> <Route path="/about" component={AboutPage} /> <Route path="/contact" component={ContactPage} /> <Route path="/login" component={LoginPage} /> <Route path="/register" component={RegisterPage} /> <Route path="/me" component={ProfilePage} /> </p> <footer> React Router v4 Browser Example (c) 2017 </footer> </p> );
然后我们来创建需要的组件:
const HomePage = () => <p>This is a Home Page</p> const LoginPage = () => <p>This is a Login Page</p> const RegisterPage = () => <p>This is a Register Page</p> const ProfilePage = () => <p>This is a Profile Page</p> const AboutPage = () => <p>This is a About Page</p> const ContactPage = () => <p>This is a Contact Page</p>
最后,写App
组件。
const App = () => ( <BrowserRouter> <BaseLayout /> </BrowserRouter> ) render(<App />, document.getElementById('root'));
如你所见,react router v4的组件还非常的易用的。
在上例中,我们在HomePage
组件的路由里使用了属性exact
。
<Route path="/" exact component={HomePage} />
这是因为v4中的路由默认都是非排他的,这一点和v3的实现思路截然不同。如果没有exact
属性,HomePage
组件和其他的组件就会同事绘制在页面上。
如,当用户点了登录连接以后,"/"
和"/login"
都满足匹配条件,对应的登录组件和Home组件就会同时出现在界面上。但是,这不是我们期待的结果,所以我们要给"/"
path加上exact
属性。
现在我们来看看非排他的路由有什么优点。假如我们有一个子菜单组件需要显示在profile页面出现的时候也出现。我们可以简单的修改BasicLayout
来实现。
const BaseLayout = () => ( <p className="base"> <header> <p>React Router v4 Browser Example</p> <nav> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/about">About</Link></li> <li> <Link to="/me">Profile</Link> <Route path="/me" component={ProfileMenu} /> </li> {/*略*/} </ul> </nav> </header> </p> );
这样我们就会看到对应于"/me"
路径的组件都绘制出来了。这就是非排他路由的好处。
排他路由是react router v3的默认实现。只有第一个匹配的路由对应的组件会被绘制。这一点也可以用react router v4的Switch
组件来实现。在Switch
组件中,只有第一个匹配的路由<Route>
或者<Redirect>
会被绘制:
import { Switch, Route } from 'react-router';<Route exact path="/" component={HomePage} />
react router v4中,提供了一个history
对象。这个对象包含了多个api,可以用来操作浏览器历史等。
你也可以在React应用里使用history
对象的方法:
history.push("/my-path") history.replace("/my-path")
用另外的方法可以写成:
<Link to="/my-path" /> <Redirect to="my-path" />
无论何时你要重定向到另外一个地址的时候,都可以使用Redirect
组件:
<Redirect to {{ pathname: '/register', search: '?utm=something', state: { referrer: someplage.com } }}>
或者,更为简单的:
<Redirect to="register" />
react router v4让开发react应用变得更加的简单。让react应用内的页面跳转更加简单。你只需要声明一个BrowserRouter
或者HashRouter
,然后在它的内部放上一系列的Route
组件,这些主键只要包含path
和component
属性。无论何时有了匹配的路由,那么它就会进行非排他的绘制(所有匹配的路由都会绘制)。你也可以把Route
放在Switch
组件里来实现排他的绘制(只有第一个匹配的路由会被绘制)。你可以在路径中传递参数,match
对象会保留这些参数。最后,所有在web中使用的路由组件都包含在react-router-dom
中。只需要引入react-router-dom
就可以使用。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
Chart.js 轻量级HTML5图表绘制工具库使用步骤详解
The above is the detailed content of Detailed explanation of steps to use React-router v4. For more information, please follow other related articles on the PHP Chinese website!