knowledge

  1. CreateContext Component data transfer
  2. UseHistory Indicates the route redirection
  3. The Location object of the current URL that the useLocation hook returns is similar to a URL
  4. Redirect Indicates route redirection
  5. UseState () status management
const [state, setState] = useState(initialState);
Copy the code

In the initialization state, the setState function in the array whose state value is equal to the initialState value passed in is used to update the state value, receives a new parameter to update the state value, and re-enqueues the render.

  • enabled

  • Initialize the

  • read

  • update

React-router-dom V5.1.0 added useHistor hook hook

The body of the

The parent component

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


// React-router-dom v5.1.0 added useHistor hook hook
class AuthExample extends React.Component {
    render () {
        return (
            <ProvideAuth>
                <Router>
                    <div>
                        <AuthButton />
                            <ul>
                                <li>
                                    <Link to="/public">Public Page</Link>
                                </li>
                            </ul>
                            <ul>
                                <li>
                                    <Link to="/protected"> Protected Page</Link>
                                </li>
                            </ul>
                            <Switch>
                                <Route path="/public">
                                    <PublicPage></PublicPage>
                                </Route>
                                <Route path="/login">
                                    <LoginPage></LoginPage>
                                </Route>
                                <PrivateRoute path="/protected">
                                    <ProtectedPage></ProtectedPage>
                                </PrivateRoute>
                            </Switch>
                    </div>
                </Router>
            </ProvideAuth>)}};Copy the code

AuthButton subcomponents

Based on the return value of useAuth, the system displays whether the login is successful and changes the status of the history route

function AuthButton () {
    let history = useHistory();
    let auth = useAuth();
    console.log(auth);
    return auth.user ? (
        <p>
            Welcome !{''}
            <button onClick={() = > { auth.signout (() => history.push('/')); }}>
                Sign out
            </button>
        </p>
    ) : (
        <p>You are not logged in.</p>)};Copy the code

PrivateRoute subcomponents

  • Children: Displays content if the user is already logged in
  • Location Indicates the route information after login
  • . The rest extension operator takes the location argument from rest, determines that the user is logged in, displays the childern content, otherwise redirects to ‘/login’, re-logs in, and passes the value state with the content of location,
// What is displayed after login
function ProtectedPage() {
    return <h3>Protected</h3>;
}
    
    
function PrivateRoute ( {children ,...rest  }) {
    let auth = useAuth();
    console.log('PrivateRoute component to start ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~');
    console.log(children);       
    console.log( { ... rest } );return (
        <Route
            { . rest }
            render = {({location } ) => auth.user ? ( children ) : (
                <Redirect to={{ pathname:"/login",state: { from:location } }} />)} ></Route>)};Copy the code

LoginPage subcomponents

  • UseHistory () Obtains routing information
  • UseLocation () gets location information
  • UseAuth () Obtains login information
  • The Location object of the current URL that the useLocation hook returns is similar to a URL
function LoginPage () {
    let history = useHistory();
    let location = useLocation();
    let auth = useAuth();
    console.log(auth);
    let { from } = location.state || { from : {pathname:'/'}};let login = () = > {
        auth.signin( () = > {
            history.replace(from); })};return (
        <div>
            <p>You must log in to view the page at { from.pathname } </p>
            <button onClick={ login} > Log in</button>
        </div>)};Copy the code

Public subcomponents

function PublicPage() {
    return <h3>Public</h3>;
}   
Copy the code

operation

createContext

Liverpoolfc.tv: zh-hans.reactjs.org/docs/contex…

const authContext = createContext();
 
 // Take the value from authContext
function useAuth () {
    return useContext(authContext);
};
Copy the code

ProvideAuth function

  • CreateContext Parent-child data transfer values are suitable for multiple levels of nesting
function ProvideAuth({ children }) {
    const auth = useProvideAuth();
    console.log(auth);
    return (
    <authContext.Provider value={auth}>{/* Create the Provider Provider in the container, which is like a tag, to produce shared data, and define the values to be shared in the value */} {children}</authContext.Provider>
    );
};
Copy the code

FakeAuth function

Initialize login information and define some variables

const fakeAuth = {
    isAuthenticated: false.// Initializes the state value
    signin(cb) {
        fakeAuth.isAuthenticated = true;            // Change the status value
        // 100ms Changes the route status
        setTimeout(cb, 100); // fake async      
    },
    signout(cb) {
        fakeAuth.isAuthenticated = false;           // Change the status value
        // 100ms Changes the route status
        setTimeout(cb, 100); }};Copy the code

UseProvideAuth function

  • Use useState() to update user data and change the status of the login route
  • SetUser manipulates data
function useProvideAuth() {
    const [user, setUser] = useState(null);

    const signin = cb= > {
      return fakeAuth.signin(() = > {
        console.log(fakeAuth);
        setUser("user");
        // Change the routing state after login
        cb();
      });
    };

    const signout = cb= > {
      return fakeAuth.signout(() = > {
        console.log(fakeAuth);
        setUser(null);
        // After login, empty the route
        cb();
      });
    };

    return {
      user,
      signin,
      signout
    };
};
Copy the code

React-router-dom Specifies whether the user logs in to perform the Redirect.

Diary 1,