根組件根據客戶端不一樣的請求網址顯示時,要卸載上一個組件,再掛載下一個組件,若是手動操做話將是一個巨大麻煩。具體過程以下圖:javascript
【根組件】 ↑ 【首頁組件】 【新聞組件】 【商品組件】
【react-router】能夠讓根組件動態的去掛載不一樣的其餘組件。(根據用戶訪問的地址動態的加載不一樣的組件)css
【官網文檔入口】:https://github.com/ReactTraining/react-routerjava
一、找到官方文檔
https://reacttraining.com/react-router/web/example/basicreact
二、安裝git
cnpm install react-router-dom --save
三、找到項目的根組件引入react-router-domgithub
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
四、複製官網文檔根組件裏面的內容進行修改 (加載的組件要提早引入)
注:exact表示嚴格匹配,不加的話,點新聞時,仍是會把首頁也加載進來web
<Router> <Link to="/">首頁</Link> <Link to="/news">新聞</Link> <Link to="/product">商品</Link> <Route exact path="/" component={Home} /> <Route path="/news" component={News} /> <Route path="/product" component={Product} /> </Router>
【src/App.js】-- 路由配置都在此處npm
import React from 'react'; import './App.css'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; //首先要引入路由模塊 import Home from './components/Home'; import News from './components/News'; import Product from './components/Product'; function App() { return ( <Router> <div> <header className="title"> <Link to="/">首頁</Link> | <Link to="/news">新聞</Link> | <Link to="/product">商品</Link> | </header> <br /><hr /> <Route exact path="/" component={Home} /> <Route path="/news" component={News} /> <Route path="/product" component={Product} /> </div> </Router> ); } export default App;
【src/components/Home.js】react-router
import React, { Component } from 'react'; class Home extends Component { constructor(props){ super(props); this.state = { }; } render() { return ( <div> 我是首頁組件 </div> ); } } export default Home;
【src/components/News.js】dom
import React, { Component } from 'react'; class News extends Component { constructor(props) { super(props); this.state = { }; } render() { return ( <div> 我是新聞組件 </div> ); } } export default News;
【src/components/Product.js】
import React, { Component } from 'react'; class Product extends Component { constructor(props) { super(props); this.state = { }; } render() { return ( <div> 我是商品組件 </div> ); } } export default Product;
【效果】:點上面導航,下面內容自動切換(自動卸載前一個組件,加載新組件)