React路由之react-router-dom

React的路由據(jù)筆者所知有react-router,react-router-dom,筆者認(rèn)為react-router-dom要比react-router好用很多

一、裝包

npm install react-router-dom --save
首先看一下最終的目錄結(jié)構(gòu)
目錄結(jié)構(gòu)

二、在src目錄下新建一個Router.js文件用來配置路由

import Page1 from './pages/Page1'
import Page2 from './pages/Page2'
import React, { Component } from 'react'
import { Route, Switch, withRouter, BrowserRouter } from 'react-router-dom'
class Router extends Component {
  constructor(props) {
    super(props)
    this.state = {
    }
  }

  render() {
    return (
      <BrowserRouter>
        <Switch>
          <Route exact path="/" component={withRouter(Page1)} />
          <Route exact path="/page2" component={withRouter(Page2)} />
        </Switch>
      </BrowserRouter>
    )
  }
}
export default Router

三、修改index.js文件

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
// import App from './App';
import Router from './Router'
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<Router />, 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();

四、在頁面?zhèn)冎械氖褂?/h1>

下邊的那種寫法都可以,前兩種傳參的話會暴露在地址欄,第三種比較優(yōu)雅,不會暴露在地址欄,但是瀏覽器刷新后參數(shù)就沒了,需要配合存儲使用。
this.props.history.push('/page2')
this.props.history.push({pathname:'/page2'}) 
this.props.history.push({pathname:"/page2",state : { id : '111' }});

五、路由傳參

this.props.history.push('/page2/' + 666 + '')
this.props.history.push({pathname:'/'}) 

上邊的寫法傳參就是要在后邊拼接
不推薦用上邊的寫法傳參,改變URL,可能導(dǎo)致路由失敗

this.props.history.push({pathname:"/page2",state : { id : '111' }});

獲取數(shù)據(jù):this.props.location.state.id

六、效果展示及代碼

頁面一page1
import React, { Component } from 'react'

export class Page1 extends Component {
  constructor(props) {
    super(props)
    this.state = {
    };
  };
  render() {
    return (
      <div style={{
        width: '100%',
        height: window.innerHeight,
        background: '#001D37',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
      }}>
        <div
          onClick={() => {
            // this.props.history.push('/page2/' + 666 + '')
            this.props.history.push({pathname:'/page2'}) 
            // this.props.history.push({pathname:"/page2",state : { id : '111' }});
          }}
          style={{
            width: '500px',
            height: '200px',
            background: '#fff',
            padding: '30px',
            borderRadius: '10px',
            lineHeight: '200px',
            textAlign: 'center',
          }}>
          我是頁面一一一一一一一
          點我可以去頁面二
        </div>
      </div>
    )
  }
}

export default Page1

頁面二page2
import React, { Component } from 'react'

export class Page2 extends Component {
  constructor(props) {
    super(props)
    this.state = {
    };
  };
  render() {
    // console.log(this.props.location.state.id)
    console.log(this.props.location.params)
    return (
      <div style={{
        width: '100%',
        height: window.innerHeight,
        background: '#001D37',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
      }}>
        <div
         onClick={()=>{
          this.props.history.push('/')
          // this.props.history.push({pathname:'/'}) 
          // this.props.history.push({pathname:"/",state : { id : '222' }});
        }}
        style={{
          width: '500px',
          height: '200px',
          background: '#ff0',
          padding: '30px',
          borderRadius: '10px',
          textAlign:'center',
          lineHeight:'200px',
        }}>
          我是頁面二二二二二二二二
          點我可以去頁面一
        </div>
      </div>
    )
  }
}

export default Page2

欲知知完整代碼如何請見GitHub

https://github.com/jade-kylin/react-router-dom-study.git

git clone https://github.com/jade-kylin/react-router-dom-study.git

執(zhí)行即可獲取到完整項目文件

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容