zoukankan      html  css  js  c++  java
  • React项目使用React-Router

    ⒈初始化React项目(略)

      请参考  初始化一个React项目(TypeScript环境)

    ⒉集成React-Router

      在React世界里,公认最好用的路由是React-Router。那我们直接来集成它吧。

    yarn add react-router history
    #如果是type环境
    yarn add react-router @types/react-router history @types/history

    ⒊配置React-Router

      在src中新建一个文件叫Router.js(如果是type环境则名称为Router.tsx):

    cd src
    cd.>Router.js #如果是type环境 cd.>Router.tsx

      代码如下:

    import {createBrowserHistory} from 'history';
    import React from 'react';
    import {Route,Router} from 'react-router';
    import App from './App';
    import Edit from './Edit';
    
    const history = createBrowserHistory()
    
    export default () => (
      <Router history={history}>
        <>
          <Route exact path="/" component={App}/>
        </>
      </Router>
    )

      然后修改index.js(type环境为index.tsx)文件,将读取的组件修改为Router:

    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    // import App from './App';
    import * as serviceWorker from './serviceWorker';
    import Router from './Router';
    
    // ReactDOM.render(<App />, document.getElementById('root'));
    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();

      刷新一下页面,运行正常

      那我们再添加一个页面Edit.js(type环境为Edit.tsx),并为它配好路由:

    Edit.js
    import React from 'react';
    
    export default () => (
      <div>Edit</div>
    )
    Router.js
    import {createBrowserHistory} from 'history';
    import React from 'react';
    import {Route,Router} from 'react-router';
    import App from './App';
    import Edit from './Edit';
    
    const history = createBrowserHistory()
    
    export default () => (
      <Router history={history}>
        <>
          <Route exact path="/" component={App}/>
          <Route path="/edit" component={Edit}/>
        </>
      </Router>
    )
  • 相关阅读:
    RPC框架实践之:Apache Thrift
    ubuntu中安装hadoop集群
    前端开发浏览器兼容问题
    3亿(int)数据-2亿(int)数据 求差集
    mvn docker 部署 每次都需要下载包的问题
    树莓派操作记录
    mysql 实现类似开窗函数的功能
    mysql 多字段更新
    go proxy转发工作中碰到的问题
    之前项目使用的轻量的goweb框架
  • 原文地址:https://www.cnblogs.com/fanqisoft/p/12022163.html
Copyright © 2011-2022 走看看