学习笔记——React Router Dom的基本使用

ref: https://medium.com/@pshrmn/a-simple-react-router-v4-tutorial-7f23ff27adf

react-router vs react-router-dom vs react-router-native

  • React Router has been broken into three packages: react-router, react-router-dom, and react-router-native.

react-router-dom

  • Router
    • BrowserRouter: The should be used when you have a server that will handle dynamic requests .
    • HashRouter: while the should be used for static websites (where the server can only respond to requests for files that it knows about).
    • History
    • example: Router components only expect to receive a single child element.
    import { BrowserRouter } from 'react-router-dom'
    ReactDOM.render((
    
      
    
    ), document.getElementById('root'))
    
  • Routes
    • path :which is a string that describes the pathname that the route matches.
    • exact: match the route compeletely. (will be default true after v5).
    • only match the pathname of location, don't care about the querystring.
    • use path-to-regexp package to determine if a route element's path prop matches the current location.
    • match object: when the route's path matched, a match object will be created
      • url: the matched part of the current location's pathname.
      • path: the route's path.
      • isExact: path===pathname.
      • params: an Object containing values from the pathname that were captured by path-to-regexp.
    • to group
    • will iterate over its children elements and only render the first one that matches the current pathname.
  • What does the render
    • component: A react component, no extra props to pass to the component.
    • render: A function that returns a React element
    • children: A function than returns a React element, this will always be rendered , regardless of whether the route's path matches the current location.
    
      
       {
           
       }
      }/>
       {
          props.match 
            ?  
            : 
      }}/>
    
    
  • path params
    • for a path in , we can define a path as path='/post/:id', if we want to capture the id of the post, we can use match.params.id ,
    • note that the captured value is a string.
  • Links
    • React Router provides a component to so that we can navigate between pages, and at the same time , it's different with using anchor element, it will not reload the whole page.

你可能感兴趣的:(学习笔记——React Router Dom的基本使用)