React项目使用React-Router

⒈初始化React项目(略)

⒉集成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>
)
上一篇:Edit Distance


下一篇:PyQt5快速上手基础篇4-将lineEdit输入框数据同步显示再label和LCD屏上面