React practice project (IV)

Time:2021-9-11

React has nearly 70000 stars on GitHub, which is the most popular front-end framework at present. I have been learning react for some time, and now I start to use react + Redux for actual combat!

Last time I talked about using Redux saga to manage asynchronous operations of Redux applications. The application still has only one home page. Now start building a new submission page and use react router for routing management

React practice project (I)
React practice project (II)
React practice project (III)
React practice project (IV)

-First, let’s build the submission page

Create Src / containers / submitentry.js

/**
 * Created by Yuicon on 2017/7/13.
 * https://github.com/Yuicon
 */
import React, {Component} from 'react';
import {Button, Form, Input, Switch, Notification} from "element-react";
import {connect} from "react-redux";
import {createEntryAction} from '../../redux/action/entries';
import './SubmitEntry.css';

@connect(
  (state) => {
    return ({
      entries: state.entries,
    });
  },
  {createEntryAction: createEntryAction}
)
export default class SubmitEntry extends Component {

  constructor(props) {
    super(props);

    this.state = {
      form: {
        title: '',
        content: '',
        original: true,
        originalUrl: null,
        english: false,
        type: 'article',
      },
    loading: false,
    };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.entries.get('saveSuccess')) {
      Notification.success({
        Title: 'success',
        Message: 'submission succeeded',
        duration: 1500
      });
      this.setState({form: {
        title: '',
        content: '',
        original: true,
        originalUrl: null,
        english: false,
        type: 'article',
      }});
    } else if (nextProps.entries.get('error')) {
      Notification.error({
        Title: 'error',
        message: nextProps.entries.get('error'),
        type: 'success',
        duration: 1500
      });
    }
    this.setState({loading: false});
  }

  handleSubmit = () => {
    this.props.createEntryAction(this.state.form);
    this.setState({loading: true});
  };

  handleChange = (key, value) => {
    this.setState({
      user: Object.assign(this.state.form, {[key]: value})
    });
  };

  render(){
    return(
      <div className="SubmitEntry-container">
        <div className="head">
          <h2>Recommend articles to Nuggets</h2>
          <p>Thank you for sharing. The review time of the article is about 1-2 working days</p>
        </div>
        <div className="entry-form">
          <Form model={this.state.form} labelWidth="80" onSubmit={this.handleSubmit}>
            < form. Item label = "share website" >
              <Input value={this.state.form.originalUrl} onChange={this.handleChange.bind(this, 'originalUrl')}/>
            </Form.Item>
            < form. Item label = "title" >
              <Input value={this.state.form.title} onChange={this.handleChange.bind(this, 'title')}/>
            </Form.Item>
            < form. Item label = "description" >
              <Input value={this.state.form.content} onChange={this.handleChange.bind(this, 'content')}/>
            </Form.Item>
            <Form.Item >
              <Switch
                value={this.state.form.original}
                onChange={this.handleChange.bind(this, 'original')}
                Ontext = "original"
                Offtext = "reprint" >
              </Switch>
            </Form.Item>
            <Form.Item >
              <Switch
                value={this.state.form.english}
                onChange={this.handleChange.bind(this, 'english')}
                Ontext = "English"
                Offtext = "Chinese" >
              </Switch>
            </Form.Item>
            <Form.Item >
              <Button type="primary" onClick={this.handleSubmit} loading={this.state.loading}>
                release
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    )
  }
}

The relevant Redux sections have been covered. I won’t repeat the introduction. Those interested can view itSample code

  • After the page is created, start using react router to manage routes

  • The first is to add dependencies

Edit package.json

//The react router DOM contains a react router
    "react-router-dom": "^4.1.1",
  • Edit app.js

/**
 * Created by Yuicon on 2017/6/25.
 */
import React, { Component } from 'react';
import {BrowserRouter as Router,Route} from 'react-router-dom'
import './App.css';
import Index from "../Index/Index";
import Header from "../Header/Header";
import SubmitEntry from "../SubmitEntry/SubmitEntry";

export default class App extends Component {

  render(){
    return(
    <Router>
      <div className="App">
        <Route component={Header}/>
        <Route exact path="/" component={Index}/>
        <Route exact path="/submit-entry" component={SubmitEntry}/>
      </div>
    </Router>
    )
  }

}

Router:

There are three types of routers. We use the commonly used browserhistory

History H5 of browserhistory
Hashhistory history of older browsers
Memoryhistory the history in the node environment is stored in memory

Route :

Each route tag corresponds to a UI page. Its responsibility is to render the corresponding UI interface when the access address of the page matches the path on the route.
and<Route component={Header}/>There is no path, which means that the header component will be rendered on each page

exact :

Exact props on the route indicates that strict matching is adopted, and the access address of the page must be the same as the path on the route
<Route exact path="/" component={Index}/>Only ‘/’ will be matched, and ‘/ submit entry’ will not be matched
<Route path="/" component={Index}/>Will match all paths starting with ‘/’

history:

common method

Push (path, [state]) adds a new entry to the history stack information.
Commonly used for page Jump, such as: this.props.history.push('/');Jump to home page

Replace (path, [state]) replaces the current entry in the history stack information
The difference with push is that the page before jump cannot be returned through the history stack

Goback() is equivalent to the browser’s back key

match:

The match object contains information about how the route matches the URL and has the following properties:

Params: object path parameter, which obtains key value pairs by parsing the dynamic part of the URL

Isexact: when bool is true, the entire URL needs to match

Path: string is used to match the path pattern and create nested < route >

URL: the matching part of a string URL for nested < link >

Commonly used to get parameters in a path
There is such a route<Route path="/:id" component={Child}/>
The ID parameter can be obtained in child in this waythis.props.match.params.id

  • epilogue

    Now we have a visible application, and most of the rest is some business code. To verify the effect, of course, you choose to deploy to the server. The next article will introduce how to deploy react applications using the docker image of nginx.

Full project code address:https://github.com/DigAg/diga…