react路由React-Router学习教程(三)

责编:menVScode 2017-07-02 22:12 阅读(1394)

<Switch>:只渲染第一个匹配的<Route>或者<Redirect>;

import React from 'react';
import {BrowserRouter as Router,Route,Link,Switch} from 'react-router-dom';
const Demo = () =>{
	return(
		<div>
			<ul>
				<li><Link to='/'>Home</Link></li>
				<li><Link to='/about'>About</Link></li>
				<li><Link to='/join'>Join</Link></li>
				<li><Link to='/call'>Call</Link></li>
			</ul>
			<hr/>
		</div>
	)
}

const DemoRouter = () =>(
	<Router>
		<div>
			<Demo />
			<Switch>
				<Route exact path='/' render={ ()=> <h2>Home</h2> } />
				<Route path='/about' render={ ()=> <h2>About</h2> } />
				<Route 
					path='/:param'
					render={
						({match})=>(
							<h2>{match.params.param}</h2>
						)
					}
				/>
				<Route render={()=><h2>页面不存在</h2>} />
			</Switch>
		</div>
	</Router>
)
export default DemoRouter;

        上述例子,如果不使用<Switch>的话,就会把匹配成功的结果都显示出来了。

<Prompt>:当离开页面,做的操作,可发出提示。Prompt属性如下:

        message:字符串,当你离开页面的时候,给出提示框。

        message:function,当你离开页面的时候,给出提示框。

        when:布尔值,当为true时Prompt组件生效。

import React from 'react';
import {BrowserRouter as Router,Route,Link,Switch,Prompt} from 'react-router-dom';
const Demo = () =>{
	return(
		<div>
			<ul>
				<li><Link to='/'>Home</Link></li>
				<li><Link to='/about'>About</Link></li>
			</ul>
			<hr/>
		</div>
	)
}

const DemoRouter = () =>(
	<Router>
		<div>
			<Demo />
			<Route exact path='/' render={ ()=> (<h2>Home</h2>) } />
			<Route path='/about' render={ ()=> <h2>About</h2> } />
			<Prompt message='你确定要离开嘛?' />
                        {/*
                            <Prompt when={false} message='你确定要离开嘛?' />
                            当when为false时,离开页面时不会出现提示框
                        */}
		</div>
	</Router>
)
export default DemoRouter;

        例子效果展示:

QQ截图20170702215223

<Redirect>:重定向

import React from 'react';
import {BrowserRouter as Router,Route,Link,Redirect,Switch} from 'react-router-dom';

const logined = false;
const DemoRedirect = () => (
	<Router>
		<div>
			<Link to='/'>Home </Link>&nbsp;
			<Link to='/old/123'>Old </Link>&nbsp;
			<Link to='/new/456'>New </Link>&nbsp;
			<Link to='/redirect/789'>Redirect </Link>&nbsp;
			<Link to='/login'>Login </Link>
			<Route exact path='/' render={()=><h2>首页</h2>} />
			<Route 
				path='/login'
				render={
					()=>(
						logined ? <h2>登陆成功</h2> : <Redirect to="/redirect/111"/>
					)
				}/>
			{/*适用于需要传参的重定向需求 param */}
			<Route 
				path='/redirect/:param'
				/*pushtrue时,重定向会将新条目推入历史记录,而不是替换当前条目,无法使用后退功能*/
				render={
					({match})=>(
						<Redirect push={false} to={`/new/${match.params.param}`}/>
					)
			} />
			{/*需要被重定向的路径,可以结合Switch,这适用于不需要传参的重定向需求*/}
			<Switch>
				<Route 
					path='/new/:param'
					render={
						({match})=>(<h2>New:{match.params.param}</h2>)
				} />
				<Redirect from='/old/:param' to='/new/123' />
			</Switch>
		</div>
	</Router>
)
export default DemoRedirect;
前端交流群: MVC前端网(menvscode.com)-qq交流群:551903636

邮箱快速注册

忘记密码