react學習系列2使用react-routerv4

飛凡的陀螺發表於2017-11-05
  1. 問:react-router,react-router-native 和 react-router-dom 的區別
    答:react-router是核心。react-router-native 和 react-router-dom是在 react-router 的基礎上針對不同執行環境做為額外補充。對於web環境使用 react-router-dom。對於開發 react-native,使用 react-router-native 即可。

  2. 官方的例子及程式碼
    web
    native

  3. 例子:手動跳轉

路由檔案 routerMap

import React from `react`
import { BrowserRouter as Router, Route, Link, Switch } from `react-router-dom`
import Home from `../Pages/Home/`
import List from `../Pages/List/`
import Detail from `../Pages/Detail/`
import NoMatch from `./404`

//  下面幾行是老式寫法,可以忽略
// import createBrowserHistory from `history/createBrowserHistory`;
// 是個用於瀏覽器導航#的歷史物件
// const history = createBrowserHistory()
// <BrowserRouter /> 其實就是<Router history={history} />

export class RouterMap extends React.Component {
  render() {
    return (
      <Router>
        <div>
          <ul>
            <li><Link to="/">Home</Link></li>
            <li><Link to="/list">List</Link></li>
          </ul>
          <hr/>
          <Switch>
            <Route exact path="/" component={Home} />
            <Route exact path="/list" component={List} />
            <Route path="/detail/:id" component={Detail} />
            <Route component={NoMatch}/>
          </Switch>
        </div>
      </Router>
    );
  }
}

入口檔案

import React from `react`;
import ReactDOM from `react-dom`;
import App from `./App`;
import {RouterMap} from "./Router/routerMap";

ReactDOM.render(<div>
  <App />
  <RouterMap />
</div>, document.getElementById(`root`));

List頁面

import React from `react`

export default class List extends React.Component {
  constructor({ match }) {
    super();
    this.state = {
      match
    }
  }

  clickHandle(item) {
    //關於history
    // http://www.jianshu.com/p/e3adc9b5f75c
    this.props.history.push(`/detail/` + item)
  }

  render() {
    const arr = [1,2,3]
    console.log(this.state.match)
    return (
      <div>
        <h3>List Page</h3>
        <ul>
          {
            arr.map((item, index) =>
              <li key={index} onClick={this.clickHandle.bind(this, item)}>{item}</li>
            )
          }
        </ul>
      </div>
    )
  }
}

Detail 頁面

import React from `react`

export default class Detail extends React.Component {
  constructor({ match }) {
    super();
    this.state = {
      match
    }
  }

  render() {
    console.log(this.state.match)
    return (
      <div>Detail Page {this.state.match.params.id}</div>
    )
  }
}

參考:http://www.jianshu.com/p/e3adc9b5f75c


相關文章