一个前端,爱跑步、爱吉他、爱做饭、爱生活、爱编程、爱南芳姑娘,爱我所爱。世间最温暖又无价的是阳光、空气与爱,愿它们能带你去更远的地方。

  • 文章
  • 心情
  • 照片墙
  • 工具
  • 开发技术分享

    React路由学习

    技术 273 2019-11-06 16:01

    1.安装react-router-dom

    $ npm i react-router-dom --save
    

    2.在页面进行引入

    import {BrowserRouter as Router,Route,Link} from 'react-router-dom'
    

    3.编写两个无状态的路由组件

    声明路由组件 一个func 相当于是一个路由组件 
    这里是无状态路由的写法 实际工作中会把路由组件单独的写成一个js来进行引入
     function Index (){
         return <h2>Jspang.com</h2>
     }
     function List (){
         return <h2>List-page</h2>
     }
    

    4.创建控制路由的组件

    function AppRouter (){
        return(
            <Router>
                <ul>
                    {/* Link 为路由的跳转 类似于a标签 */}
                    <li><Link to='/'>首页</Link></li>
                </ul>
    
                {/* exact 为精准定位 必须为/ 才能进行匹配 
                    Route 为路径的指引
                    component 为上面绑定的组件
                    path 为路径
                */}
                <Route path="/" exact component = {Index} />
                {/* :id 设置规则 不传不跳转 */}
                <Route path="/list/:id"  component = {List} />
                <Route path="/home/"  component = {Home} />
            </Router>
        )
    }
    // 暴露出去
    export default AppRouter;
    

    路由的URL传参

    1.在路由指引组件上声明传参规则,不传则不会跳转

    <Route path="/list/:id"  component = {List} />
    

    2.在跳转过来的页面接收值

    在生命周期中接收 路由传递的值
     componentDidMount(){
    let ReadID = this.props.match.params.id
            console.log(ReadID)
    }
    

    3.重新设置state的值可以在声明周期中使用this.setState({}),前提是设置的数据需要在state中声明好

    4.路由的重定向 引入RediRect

    import {Link,Redirect } from 'react-router-dom'
    编程式重定向
    this.props.history.push('/home/')
    标签重定向 在render最外层标签中写入
    <Redirect to="/home/" /> 
    

    路由的嵌套

    1.在子路由中建立孙路由直接引入即可

    2.根据后台返回的数组来动态渲染路由

    模拟一组数据

        let routeConfig =[
            {path:'/',title:'博客首页',exact:true,component:Index},
            {path:'/video/',title:'视频教程',exact:false,component:Video},
            {path:'/work/',title:'职场技能',exact:false,component:Work}
          ]
        return(
            <Router>
                <div className="mainDiv">
                    <div className="leftNav">
                        <h3>一级导航</h3>
                        <ul>
                            {
                                routeConfig.map((item,index)=>{
                                    return (
                                        <li key={index}>
                                            <Link to={item.path}>{item.title}</Link>
                                        </li>
                                    )
                                })
                            }
                        </ul>
                    </div>
                </div>
    
                <div className="rightMain">
                    {
                        routeConfig.map((item,index)=>{
                            return (
                                <Route path={item.path}  
                                       exact={item.exact} 
                                       component={item.component} />
                            )
                        })
                    }
                </div>
            </Router>
    



    路由跳转的四种方式:

    1.通过Link标签跳转,在上面已经有过相关说明

    2.在页面中,可以通过WithRouter 来跳转

    示例:

    	import { withRouter } from "react-router-dom";
    
        class Home extends Component{
     		<button onClick={this.goForward}>下一级</button>
            goForward = () => {
                this.props.history.goForward()  //函数式路由
                {/* 
                    this.props.history.go(0)   //正数表示调用几次goForward,负数表示调用几次goBack(),0表示刷新当前页面;
                    this.props.history.goBack()  //返回上一级
                    this.props.history.push('/home') //到哪去
                    this.props.history.replace()  //替换当前路径 历史记录不再会有替换之前的路径
                */}
            }
        }
    	
    	export default withRouter(Home) 
    

    3.在组件中,前提是使用redux和

    前置条件 使用了redux-thunk和connected-react-router

    1.
    import { connect } from "react-redux";
    import { push } from "connected-react-router";
    2.
    export default connect(mapStoreStateToProps)(Nav);
    
    3.
      linkTo = (route) => {
        console.log(route);
        this.props.dispatch(push(route.path));
      };
    

    4.在redux中进行跳转:

    方法同3

    5.在JS文件中(axios拦截器中,路由跳转)

    import { push } from "connected-react-router";
    import store from "../../store/index"; //初始化redux创建需要用它的dispatch
    store.dispatch(push("/Route2"));
    

    package.json参考:

    {
      "name": "combine",
      "version": "0.1.0",
      "private": true,
      "dependencies": {
        "@testing-library/jest-dom": "^4.2.4",
        "@testing-library/react": "^9.5.0",
        "@testing-library/user-event": "^7.2.1",
        "axios": "^0.20.0",
        "connected-react-router": "^6.8.0",
        "history": "^4.10.1",
        "react": "^16.13.1",
        "react-dom": "^16.13.1",
        "react-redux": "^7.2.1",
        "react-router": "^5.2.0",
        "react-router-dom": "^5.2.0",
        "react-scripts": "3.4.1",
        "redux": "^4.0.5",
        "redux-thunk": "^2.3.0"
      },
      "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject"
      },
      "eslintConfig": {
        "extends": "react-app"
      },
      "browserslist": {
        "production": [
          ">0.2%",
          "not dead",
          "not op_mini all"
        ],
        "development": [
          "last 1 chrome version",
          "last 1 firefox version",
          "last 1 safari version"
        ]
      }
    }