React路由配置

目前前端项目都是SPA项目,而单页应用就少不了路由配置,因为单页应用的页面不会刷新页面,而是根据路由的切换来更换页面组件内容的显示。参考网址

1.引入路由包
npm install --save react-router react-router-dom

react-router:是基本的router包,里边函的内容较多,但是在网页开发中有很多用不到,现在的市面上的课程讲的基本都是这个包的教程。

react-router-dom:随着react生态环境的壮大,后出现的包,这个包比react-router包轻巧了很多。`

注意:其实安装了react-router包就不用安装了react-router-dom包了,这里只是为了给大家一个提示,所以安装了两个包。在实际开发中,请根据需要进行安装。安装时使用--save,因为这是要在生产环境中使用的。

2.设置路由配置文件

src目录下新建一个Router/index.js文件用于管理路由,这里需要引入一些对应的组件,比如首页啊,关于我们页面啊之类的页面,还有路由包文件。react路由中的Switch和exact的使用

  • Routerhistory是必需的props
  • Switch表示只渲染第一个与当前地址匹配的
  • Routeprops path为路径,component为路径对应的页面
  • exact属性表示精确匹配
import Page1 from '../container/Page1';
import Page2 from '../container/Page2';
import React from 'react';
import {Router,Route,Switch,Redirect} from 'react-router-dom';
import { createHashHistory } from "history";
const history = createHashHistory();

class RouterConfig extends React.Component{
    render(){
        return(
            
                
                    (
                        
                    )}/>
                    
                    
                
            
        )
    }
}
export default RouterConfig;
3.在入口文件引入路由配置文件
import RouterConfig from './router/index.js';
ReactDOM.render(, document.getElementById('root'));
4.在各组件中使用路由
  • 第一个页面
  • 第二个页面

你可能感兴趣的:(react,reactjs)