【工具篇】React-Router5路由使用教程

mind_programmonkey 2020-11-13 04:19:15
工具 react 路由 router react-router5


【工具篇】React-Router5路由使用教程

自我介绍

React-Router作为React体系的一个重要部分,是一个路由库。其可管理URL,实现组件的切换和状态的变换。

又拖更了好久好久了~~
在这里插入图片描述

一、React-Router和React-Router-dom的选择

React-Router

React-router提供了一些router的核心api,包括Router, Route, Switch等,但是它没有提供dom操作进行跳转的api。

React-Router-dom

React-router-dom提供了BrowserRouter, Route, Link等api,我们可以通过dom的事件控制路由。例如点击一个按钮进行跳转,大多数情况下我们是这种情况,所以在开发过程中,我们更多是使用React-router-dom。

二、准备react应用

1.建立react应用

npx create-react-app my-app
cd my-app

2.下载react-router-dom

yarn add react-router-dom

3.在vscode中安装插件react-native

三、路由的基本用法

1.效果展示

2.代码结构

  • REACT-ROUTER-DEMO
    • index.js
    • src
      • pages
        • react_router_demo1
          • demo.js
          • home.js
          • news.js
          • user.js

a.demo.js

import React from 'react';
import {

BrowserRouter as Router,
Route,
Link
} from "react-router-dom";
import Home from './home';
import News from './news';
import Users from './user';
class demo extends React.Component {

constructor(props) {

super(props);
this.state = {
 };
}
render() {

return (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/news">News</Link>
</li>
<li>
<Link to="/users">Users</Link>
</li>
</ul>
<hr/>
<Route exact path="/">
<Home />
</Route>
<Route path="/news">
<News />
</Route>
<Route path="/users">
<Users />
</Route>
</div>
</Router>
);
}
}
export default demo;

b.home.js

import React from 'react';
class home extends React.Component {

constructor(props) {

super(props);
this.state = {
 };
}
render() {

return (
<div>
这是主页页面的内容
</div>
);
}
}
export default home;

c.news.js

import React from 'react';
class news extends React.Component {

constructor(props) {

super(props);
this.state = {
 };
}
render() {

return (
<div>
这是新闻页面
</div>
);
}
}
export default news;

d.user.js

import React from 'react';
class user extends React.Component {

constructor(props) {

super(props);
this.state = {
 };
}
render() {

return (
<div>
这是用户页面
</div>
);
}
}
export default user;

e.index.js

import React from 'react';
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
import Demo from './pages/react_router_demo1/demo';
ReactDOM.render(
<React.StrictMode>
<Demo />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

四、路由的嵌套用法

1.效果展示

2.代码结构

REACT-ROUTER-DEMO

  • index.js
  • src
    • pages
      • react_router_demo2
        • Demo.js
        • home.js
        • news.js
        • Newsone.js
        • Newstwo.js
        • route_config.js
        • user.js

a.route_config.js

import Home from './home';
import News from './news';
import Newsone from './Newsone';
import Newstwo from './Newstwo';
import Users from './user';
const routes = [
{

path:"/",
exact:true,
component:Home
},
{

path:"/news",
component:News,
routes:[
{

path:"/news/news_1",
component:Newsone
},
{

path:"/news/news_2",
component:Newstwo
}
]
},
{

path:"/users",
component:Users
}
];
export default routes;

b.news.js

import React from 'react';
import {

Route,
Link
} from "react-router-dom";
class news extends React.Component {

constructor(props) {

super(props);
this.state = {
 };
}
render() {

return (
<div>
<h2>这是新闻页面</h2>
<ul>
<li>
<Link to="/news/news_1">news1</Link>
</li>
<li>
<Link to="/news/news_2">news2</Link>
</li>
</ul>
{

this.props.routes.map((value, key) => {

return <Route key={
key}
exact
path={
value.path}
render={
props=>(
<value.component {
...props} routes={
value.routes} />
)}
/>
})
}
</div>
);
}
}
export default news;

c.Newsone.js

import React from 'react';
class Newsone extends React.Component {

constructor(props) {

super(props);
this.state = {

};
}
render() {

return (
<div>
新闻1的内容
</div>
);
}
}
export default Newsone;

d.Newstwo.js

import React from 'react';
class Newstwo extends React.Component {

constructor(props) {

super(props);
this.state = {

};
}
render() {

return (
<div>
新闻2的内容
</div>
);
}
}
export default Newstwo;

e.Demo.js

import React from 'react';
import {

BrowserRouter as Router,
Route,
Link
} from "react-router-dom";
import routes from './route_config';
class Demo extends React.Component {

constructor(props) {

super(props);
this.state = {

};
}
render() {

return (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/news">News</Link>
</li>
<li>
<Link to="/users">Users</Link>
</li>
</ul>
<hr/>
{

routes.map((route,key)=>{

if(route.exact){

return <Route key={
key} exact path={
route.path}
render={
props=>(
<route.component {
...props} routes={
route.routes} />
)}
/>
}
else{

return <Route key={
key} path={
route.path}
render={
props=>(
<route.component {
...props} routes={
route.routes} />
)}
/>
}
})
}
</div>
</Router>
);
}
}
export default Demo;

f.index.js

import React from 'react';
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
import Demo from './pages/react_router_demo2/Demo';
ReactDOM.render(
<React.StrictMode>
<Demo />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

五、React Router URL传值

1.效果展示

2.代码结构

在上述代码的基础上对home.js进行修改,以及route_config.js修改 以及添加Info.js文件。

a.route_config.js

对其修改,再添加下列代码

 {

path:"/Info/:id",
component:Info
}

b.home.js

import React from 'react';
import {

BrowserRouter as Router,
Route,
Link
} from "react-router-dom";
class home extends React.Component {

constructor(props) {

super(props);
this.state = {
 };
}
render() {

return (
<div>
这是主页页面的内容
<ul>
<li>
<Link to="/Info/lcz">路由传值:lcz</Link>
</li>
<li>
<Link to="/Info/zcl">路由传值:zcl</Link>
</li>
</ul>
</div>
);
}
}
export default home;

c.Info.js

import React from 'react';
import {
withRouter} from 'react-router-dom';
class Info extends React.Component {

constructor(props) {

super(props);
this.state = {

};
}
componentDidMount(){

console.log(this.props.match.params.id)
}
render() {

return (
<div>
<h3>Info:{
this.props.match.params.id}</h3>
</div>
);
}
}
export default Info;

注意:此处用this.props.match.params来取值

六、React Router 404请求配置

在上述的基础上,在Demo.js中添加一个新页面,并添加一个未配置的路由。

1.效果展示

2.代码结构

a.Demo.js

在其中添加一个新的Link。

<li>
<Link to="/lcz">个人中心</Link>
</li>

并在下方路由上添加一个Switch

 <Switch>
{

routes.map((route,key)=>{

if(route.exact){

return <Route key={
key} exact path={
route.path}
render={
props=>(
<route.component {
...props} routes={
route.routes} />
)}
/>
}
else{

return <Route key={
key} exact path={
route.path}
render={
props=>(
<route.component {
...props} routes={
route.routes} />
)}
/>
}
})
}
</Switch>

route_config.js中追加以下代码

{

component:NotMatch
},

并配置好NotMatch.js的页面

import React from 'react';
class NotMatch extends React.Component {

constructor(props) {

super(props);
this.state = {

};
}
render() {

return (
<div>
404
</div>
);
}
}
export default NotMatch;

最后,还是要保持更新呀!!!努力努力努力!!!
在这里插入图片描述

版权声明
本文为[mind_programmonkey]所创,转载请带上原文链接,感谢
https://codingchaozhang.blog.csdn.net/article/details/108569707

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple