React Router 学习笔记

技术要点

1、嵌套路径的实现

  • 在父路径上用this.props.children,来插入子路径内容
  • IndexRoute 组件:实现访问根路径,嵌套IndexRoute组件。

2、跳转到其他路由,在路由内

  • RedirectRoute 组件
  • IndexRedirectRoute 组件
  • Link 组件

3、跳转到其他的路由页面,在事件内代码实现

  • 使用browserHistory.push
  • 使用context对象

4、Link 组件的激活状态下的样式

  • activeStyle
  • activeClassName
  • onlyActiveOnIndex={true} 相当于 IndexLink 组件

5、history属性

用来监听浏览器地址栏的变化,并将URL解析成一个地址对象,供React Router匹配

  • browserHistory : 显示正常的路径 example.com/some/path
  • hashHistory : 路由将通过URL的hash部分(#)切换,example.com/#/some/path
  • createMemoryHistory

6、path属性

  • :paramName
    • 匹配URL的一部分,直到遇到下一个/?#为止.
    • 通过this.props.params.paramName取出
  • () : 这个部分是可选的
  • * : 匹配任意字符
  • ** : 匹配任意字符,直到下一个/?#为止。
<Route path="/hello/:name">
// 匹配 /hello/michael
// 匹配 /hello/ryan

<Route path="/hello(/:name)">
// 匹配 /hello
// 匹配 /hello/michael
// 匹配 /hello/ryan

<Route path="/files/*.*">
// 匹配 /files/hello.jpg
// 匹配 /files/hello.html

<Route path="/files/*">
// 匹配 /files/ 
// 匹配 /files/a
// 匹配 /files/a/b

<Route path="/**/*.jpg">
// 匹配 /files/hello.jpg
// 匹配 /files/path/to/file.jpg

7、path属性的获取

  • /hello/:name : this.props.params.name
  • /hello?bar=baz : this.props.location.query.bar

8、路由的钩子

进入路由触发Enter,离开路由触发Leave

  • 用来做登录认证,没有登录跳转到登录页面
  • 当用户离开一个路径的时候,跳出提示框,要求用户确认是否离开

9、DEMO

import React from 'react';
import {render} from 'react-dom';
import {Router,Route,IndexRoute} from 'react-router';
import {Redirect,IndexRedirect} from 'react-router';
import {browserHistory,hashHistory} from 'react-router';
import {Link,IndexLink} from 'react-router';

//----------------组件NavLink------
const NavLink = React.createClass({
    render(){
        return (<Link {...this.props} activeStyle={{color:'red'}} />)
    }
});

//---------------组件Home-------
const Home = React.createClass({
    render(){
        return (<h1>Home Page</h1>)
    }
});

//--------------组件User---------
const User = React.createClass({

    // ask for 'router' from context
    contextTypes:{
        router: React.PropTypes.object
    },

    handleSubmit(event){
        let userId = event.target.elements[0].value;
        let userName = event.target.elements[1].value;
        const path = `/user/${userId}/${userName}`;

        //*********
        //* 代码跳转到指定路径的路由
        //*********

         browserHistory.push(path);   //或 this.context.router.push(path)
    },
    render(){
        return (
            <div>
        <ul>
          <li><NavLink to='/user/123/zhang'>测试用户1</NavLink></li>
        </ul>

                <form onSubmit={this.handleSubmit}>
                    <input type='text' placeholder='userId' />
                    <input type='text' placeholder='userName' />
                    <button type='submit'>submit</button>
                </form>

                {this.props.children}
            </div>
        )
    }
});

//--------------组件UserInfo------
const UserInfo = React.createClass({
    componentDidMount() {
                //**********
                //** 设置Leave回调处理
                const {router,route} = this.props;
                router.setRouteLeaveHook(route,this.routeWillLeave);
  },
    routeWillLeave(nextLocation){
        // true 不会停留在当前页面
        //  false 继续续停留当前页面,
        // 否则,返回一个字符串,会显示给用户,让其自己决定
        let userId = this.props.params.userId;

        if (userId === '1') {
            return true;
        }
        return '测试弹出提示字符串';
    },
    render(){
        return (
            <div>
                <div>用户编号:{this.props.params.userId}</div>
                <div>用户名称:{this.props.params.userName}</div>
            </div>
        )
    }
});

//---------------根组件App--------
const App = React.createClass({
    render(){
        return (
            <div>
                <ul>
                    <li><NavLink to='/' onlyActiveOnIndex={true}>HOME</NavLink></li>
                    <li><NavLink to='/user' >User</NavLink></li>
                    <li><NavLink to='/redirect'>Redirect To User Page</NavLink></li>
                    <li><NavLink to='/redirect/Home'>Redirect To Home</NavLink></li>
                    <li><NavLink to='/enter'>Test Enter Hook To Home</NavLink></li>
                </ul>

                {this.props.children}
            </div>
        )
    }
});

//--------------路径的Entry处理-------------------
const requireAuth = (nextState,replace) => {
    //*******
    // 可以做一些条件判断处理,比如是否为管理员
    // 然后可以跳转到相应的路径
    //*******

    replace('/');   //跳转路径 replace({pathname:'/'});
};

//--------------路径设置----------
const routes = (
    <Route path='/' component={App}>
        <IndexRoute componnet={Home} />
        <Route path='user' component={User} >
            <Route path=':userId/:userName' component={UserInfo} />
        </Route>
        <Route path='redirect'>
            <IndexRedirect to='/user' />
            <Redirect from='home' to='/' />
        </Route>

        <Route path='enter' onEnter={requireAuth} />

    </Route>
);


render(
  <Router history={browserHistory} routes={routes} />,
  document.getElementById('app')
);



  • 注意html文件中引用的bundle.js文件的绝对路径:<script src='/bundle.js' />
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容