react route example-1

1. Basic

   
       
    Ï

2.URL Parameters


    } />


function Child() {
  // We can use the `useParams` hook here to access
  // the dynamic pieces of the URL.
  let { id } = useParams();

  return (
    

ID: {id}

); }

3.Nesting
The path let us build paths that are relative to the parent route, while the url lets us build relative links

image.png

function Topics() {
  // The `path` lets us build  paths that are
  // relative to the parent route, while the `url` lets
  // us build relative links.
  let { path, url } = useRouteMatch();

  return (
    

Topics

  • Rendering with React
  • Components
  • Props v. State

Please select a topic.

); }
function Topic() {
  // The  that rendered this component has a
  // path of `/topics/:topicId`. The `:topicId` portion
  // of the URL indicates a placeholder that we can
  // get from `useParams()`.
  let { topicId } = useParams();

  return (
    

{topicId}

); }

4. Redirect

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  Redirect,
  useHistory,
  useLocation,
} from "react-router-dom";

// This example has 3 pages: a public page, a protected
// page, and a login screen. In order to see the protected
// page, you must first login. Pretty standard stuff.
//
// First, visit the public page. Then, visit the protected
// page. You're not yet logged in, so you are redirected
// to the login page. After you login, you are redirected
// back to the protected page.
//
// Notice the URL change each time. If you click the back
// button at this point, would you expect to go back to the
// login page? No! You're already logged in. Try it out,
// and you'll see you go back to the page you visited
// just *before* logging in, the public page.

export default function AuthExample() {
  return (
    
      
  • Public Page
  • Protected Page
); } const fakeAuth = { isAuthenticated: false, authenticate(cb) { fakeAuth.isAuthenticated = true; setTimeout(cb, 100); // fake async }, signout(cb) { fakeAuth.isAuthenticated = false; setTimeout(cb, 100); }, }; function AuthButton() { let history = useHistory(); return fakeAuth.isAuthenticated ? (

Welcome!{" "}

) : (

You are not logged in.

); } // A wrapper for that redirects to the login // screen if you're not yet authenticated. function PrivateRoute(props) { const { children, ...rest } = props; return ( { return fakeAuth.isAuthenticated ? ( children ) : ( ); }} /> ); } function PublicPage() { return

Public

; } function ProtectedPage() { return

Protected

; } function LoginPage() { let history = useHistory(); let location = useLocation(); let { from } = location.state || { from: { pathname: "/" } }; let login = () => { fakeAuth.authenticate(() => { history.replace(from); }); }; return (

You must log in to view the page at {from.pathname}

); }

你可能感兴趣的:(react route example-1)