• 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>
    )
  • 相关阅读:
    【模拟】HDU 5752 Sqrt Bo
    【数学】HDU 5753 Permutation Bo
    【模拟】Codeforces 706A Beru-taxi
    【二分】Codeforces 706B Interesting drink
    【动态规划】Codeforces 706C Hard problem
    【字典树】【贪心】Codeforces 706D Vasiliy's Multiset
    【中国剩余定理】POJ 1006 & HDU 1370 Biorhythms
    计算机存储单位
    转载_Linux下查看文件和文件夹大小
    反问题_不适定_正则化
  • 原文地址:https://www.cnblogs.com/fanqisoft/p/12022163.html
Copyright © 2020-2023  润新知