This is the second day of my participation in the August Text Challenge.More challenges in August

preface

React Small White because of my limited skills, if you find any mistakes or questions, welcome to point out or comment! Thank you very much!

The React of scaffolding

Create the project and start the React project

NPM i-g create-react-app

Step 2 switch to the directory where you want to create the project and run the following command:

create-react-app hello-react

yarn create react-app hello-react

Step 3, go to the project folder: CD hello-React

Step 4: Start the project: NPM start or YARN Start

Configure the agent

1. Step 1: Create a proxy profile

Create a configuration file under SRC: SRC/setupproxy.js

2. Write setupproxy.js to configure specific proxy rules:

const proxy = require('http-proxy-middleware')

module.exports = function(app) {
  app.use(
    proxy('/api1', {  // API1 is the request that needs to be forwarded (all requests with/API1 prefix are forwarded to 5000)
      target: 'http://localhost:5000'.// Configure the forwarding target address (the server address that can return data)
      changeOrigin: true.// Controls the value of the host field in the request header received by the server
      /* When changeOrigin is set to true, the host in the request header received by the server is: localhost:5000 The default changeOrigin value is false, but we usually set the changeOrigin value to true */
      pathRewrite: {'^/api1': ' '} // Remove the request prefix to ensure that the backend server is normal request address (must be configured)
    }),
    proxy('/api2', { 
      target: 'http://localhost:5001'.changeOrigin: true.pathRewrite: {'^/api2': ' '}}}))Copy the code

Description:

  1. Advantages: Multiple proxies can be configured to flexibly control whether requests go through proxies.
  2. Disadvantages: Cumbersome configuration and prefix must be added when the front-end requests resources.

React-router

SPA

  1. React is a single Page Web application (SPA).
  2. The entire application has only one complete page.
  3. Clicking on a link in a page does not refresh the page, only a partial update of the page.
  4. The data needs to be retrieved via Ajax requests and presented asynchronously on the front end.

The front-end routing

The concept of routing comes from the server, where routing describes the mapping between urls and processing functions.

In Web front-end single-page application SPA, routing describes the mapping between URL and UI. This mapping is one-way, that is, THE CHANGE of URL causes UI update (no page refresh is required).

There are two implementations of front-end routing: Hash and History

Hash implementation

  • Hash is the hash (#) and subsequent part of the URL that is used as an anchor to navigate within the page. Changing the hash part of the URL does not cause a page refresh
  • Listen for URL changes through the Hashchange event, and there are only a few ways to change a URL: by moving the browser forward or backward, by passing<a>The hashChange event is triggered when the tag changes the URL, or when the URL is changed via window.location

Advantages and disadvantages of Hash:

Advantages: Simple implementation and good compatibility (compatible with Internet Explorer 8) Most front-end frameworks provide hash routing without any configuration or development on the server side, and no other requests are initiated except resource loading and Ajax requests

Disadvantages: For some operations requiring redirection, the backend cannot obtain hash content, leading to the background unable to obtain data in THE URL. A typical example is that the oauth authentication server of wechat public account cannot accurately track the front-end routing information. The need for anchor function conflicts with the current routing mechanism

The history to achieve

The history advantages and disadvantages of

Advantages: Parameters in the URL will not be lost during redirection. The back end can get this data. Most of the preceding frameworks provide routing implementations of the History pattern. The back end can accurately track the routing information by using history.state to obtain the status information corresponding to the current URL

Disadvantages: Less compatible than hash routing (compatible with IE10 only) requires back-end support and returns HTML documents each time

Let me just say the difference

hash history
Change only the content after # You can set any URL of the same origin
The new value cannot be the same as the old value, and the same value does not trigger an action to add records to the stack The old and new values can be the same, and pushSate will be added to the stack
No changes are required for the server If the server is not responding to data or resources when refreshing, 404 will be generated. You need to modify the server and configure different routes accordingly.
That is, the request is not sent Will send a request to the server, avoid 404 server should do processing. When no resource is matched, the same HTML page should be returned.

react-router-dom

  1. React plugin library.
  2. Designed to implement a SPA application.
  3. React based projects almost always use this library.

Install yarn add react-router-dom

Built-in component –Link

1.The navigation area is Link label <Link className="list-group-item" to="/about">About</Link>
2.The display area writes Route labels to match paths <Route path="/about" component={About}/>
3.The outermost part of <App> wraps a <BrowserRouter> or <HashRouter>//index.js
  ReactDOM.render(
    <BrowserRouter>
        <App/>
    </BrowserRouter>.document.getElementById('root'))Copy the code

Built-in component –NavLink

Same as Link

NavLink enables routing links to be highlighted by specifying the style name via activeClassName

<NavLink activeClassName="atguigu" className="list-group-item" to="/about">About</NavLink>

// Encapsulate the component
//props has children children, which happens to be the name of the NavLink property to display text content
<NavLink activeClassName="atguigu" className="list-group-item"  {. this.props} / >
/ / call
<MyNavLink to="/about">About</MyNavLink>
Copy the code

Built-in component — Switch

1. Typically, there is a one-to-one relationship between path and Component.

2.Switch improves route matching efficiency (single match). When you find it, you don’t look anymore

Route registration without Switch package: All routes are displayed if no match is found

Specific coding
<Route path="/about" component={about}/> <Route path="/ Home" component={Home}/> <Route path="/home" component={Test}/> </Switch>Copy the code

Built-in component Redirect

At the bottom of all route registrations, Redirect to the route specified when all routes fail to match.

Specific coding
<Switch>
  <Route path="/about" component={About}/>
  <Route path="/home" component={Home}/>
  <Redirect to="/about"/>
</Switch>
Copy the code

Fix missing page style for multilevel path refresh

  1. Public /index.html does not write./ write/(common)
  2. Public /index.html does not write./ write %PUBLIC_URL%
  3. Using HashRouter (not recommended)
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<link rel="stylesheet" href="/css/bootstrap.css">
    
  ReactDOM.render(
    <HashRouter>
      <App/>
    </HashRouter>,
    document.getElementById('root')
  )
Copy the code

Strict matching and fuzzy matching of routes

  1. Fuzzy matching is used by default (simple note: [input path] must contain [matched path], and the order must be consistent)
  2. Enable strict matching:

<Route exact path="/about" component={About}/>

  1. Strict matching Do not enable strict matching. You need to enable strict matching again. In some cases, secondary routes cannot be matched

Embedded routines by

  1. When registering a child route, enter the path value of the parent route
  2. Routes are matched in the order in which they are registered
// Child routing
<Switch>
  <Route path="/home/news" component={News}/>
  <Route path="/home/message" component={Message}/>
  <Redirect to="/home/news"/>
</Switch>
Copy the code

The routing component passes parameters

  1. Params parameters

    Routing Link (parameters) to carry: < Link to = ‘/ demo/test/Tom / 18’} > details < / Link >

    Receive parameters: this.props.mate.params

  2. The search parameters

    Route Link (with parameters) : details < / Link >

    Receive parameters: this props. The location. The search

    Note: Search obtained is a Urlencoded string, which needs queryString parsing

  3. The state parameter

Routing Link (parameters) to carry: < Link to = {{the pathname: ‘/ demo/test, the state: {name:’ Tom ‘, age: 18}}} > details < / Link >

Receive parameters: this props. The location. The state

Note: Parameters can also be retained after refreshing

Specific code:
messageArr.map((msgObj) = >{
  return (
    <li key={msgObj.id}>{/* Pass the params parameter to the routing component */}<Link to={` /home/message/detail/ ${msgObj.id} / ${msgObj.title} `} >{msgObj.title}</Link>{/* Pass the search parameter to the routing component */}<Link to={` /home/message/detail/?id=${msgObj.id}&title=${msgObj.title}`} >{msgObj.title}</Link>{/* Pass the state argument to the routing component */}<Link to={{pathname:'/home/message/detail',state:{id:msgObj.id.title:msgObj.title}}} >{msgObj.title}</Link>
    </li>) {})/* Declare the params parameter to be received */}
<Route path="/home/message/detail/:id/:title" component={Detail}/>

{/* The search parameter does not need to be declared as receiving}
<Route path="/home/message/detail" component={Detail}/>

{/* The state parameter does not need to be received}
<Route path="/home/message/detail"Component = {Detail} / > child componentsimport qs from 'querystring'
export default class Detail extends Component {
    render() {
        // Accept the params parameter
        const {id,title} = this.props.match.params 

        // Accept the search argument
        const {search} = this.props.location
        const {id,title} = qs.parse(search.slice(1))

        // Receive the state argument
        const {id,title} = this.props.location.state || {}

        const findResult = DetailData.find((detailObj) = >{
            return detailObj.id === id
        }) || {}
        return (
            <ul>
                <li>ID:{id}</li>
                <li>TITLE:{title}</li>
                <li>CONTENT:{findResult.content}</li>
            </ul>)}}Copy the code

Programmatic routing navigation

  • Push adds a stack to history, which can be returned to the previous stack
  • Replace jumps do not form a history and cannot go back to the previous level.
// Use the API on this.prosp.history to jump, forward, and backward the operation route
  this.prosp.history.push()  / / push view
        //push jump + takes params
        this.props.history.push(`/home/message/detail/${id}/${title}`)
        //push jump + takes the search argument
        this.props.history.push(`/home/message/detail? id=${id}&title=${title}`)
        // Push jump + takes the state argument
        this.props.history.push(`/home/message/detail`,{id,title})

  this.prosp.history.replace()  / / replace view
        //replace jump + carries params arguments
        this.props.history.replace(`/home/message/detail/${id}/${title}`)
        //replace jump + takes the search argument
        this.props.history.replace(`/home/message/detail? id=${id}&title=${title}`)
        //replace jump + takes the state argument
        this.props.history.replace(`/home/message/detail`,{id,title})

  this.prosp.history.goBack()  / / back to back
  this.prosp.history.goForward() / / to go forward
  this.prosp.history.go(n)  // Negative means backward and positive means forward
Copy the code

Differences between BrowserRouter and HashRouter

  1. The underlying principle is different:
    • BrowserRouter uses the H5 History API and is not compatible with IE9 and below.
    • A HashRouter uses a hash of a URL.
  2. Path is represented in different ways
    • BrowserRouter has no # in its pathFor example: localhost: 3000 / demo/test
    • The path to the HashRouter contains #For example: localhost: 3000 / # / demo/test
  3. Impact on route State parameters after refreshing
    • BrowserRouter has no effect because state is stored in the History object.
    • [Bug Mc-103866] – HashRouter refresh causes loss of route state parameter.
  4. Note: A HashRouter can be used to resolve some path error-related problems.