Eight, redux

Note: ① ② ③

Documents: cn.redux.js.org/

1. What is redux

1) Redux is a state container that provides javascript applications with a predictable (given a fixed input, there must be a fixed result) state container. 2) Centrally manage the state of multiple components in React. 3) Redux is a JS library dedicated to state management (not the React plugin library can be used in other JS frameworks such as VUE, but mostly used in React).

2. When to use redux?

1) When the state of a component needs to be shared; 2) The state of a component needs to be available anywhere; 3) A component needs to change its global state; 4) One component needs to change the state of another component.

3. Redux’s Three Principles

1) Single data source: The state of the entire application is stored in an object tree that only exists in a single store; 2) State is read-only: The only way to change State is to fire an action, which is a common object that describes what has happened; 3) Use pure functions to perform modifications: To describe how actions change the state tree, you need to write reducers(pure functions that accept previous states and actions).

4, redux commonly used concepts

1) Store: Manages the state of the entire application. The Store provides a method dispatch(), which sends an action to change the state of the Store, and then getState() to retrieve the latest state. 2) Action: It is the only way to change the state. The server’s various pushes, and the user’s actions, will eventually be converted into a series of actions, and these actions will be executed in order; 3) Reducer: the Reducer is used to modify state. Reducer is a function that takes the Action and the current State as parameters and returns a new State.

5, redux common methods

CreateStore () Creates a Redux store to store all state in an app. An app can only have one store. The function returns the store object; 2) getState(); 3) Dispatch () the action, which is the only way to change the state; 4) Subscribe () adds a change listener, which is executed whenever the store changes.

6. Redux the execution process

7, use,

1) download

npm install –save redux

2) Create file redux

① Redux — > Reduc.js set the result returned by data processing

// Create data
var obj={
    name:"Xiao Ming",age:22
}
// Exposure in ES6; (Data must have two parameters, using the default values of the parameters in ES6)
export function data(state=obj.age,action){// Action to invoke the modified mode
    // There will be a lot of changes later on. Action.type determines which changes to make
    switch(action.type){// Type is the type (meaning what type do you modify)
        default:
            return state;// Return the result
            break; }}Copy the code

Create store (redux — >store.js)

// export (export);
import {createStore} from "redux";
// Introduce the exposed data
import {data} from "./reducer"
// Instantiate it and use it outside
export var store=createStore(data);// Pass the data in and associate them with modules
Copy the code

(3) Called in a component

import React, { Component } from 'react'
import {store} from '.. /redux/store'
export default class redux extends Component {    
	constructor(props){        
	super(props);        
		this.state={            
			text:store.getState()        
		}    
	}    
	render() {        
		return (            
			<div>                
				<h1>Rudex</h1>                
				{this.state.text}            
			</div>)}}Copy the code

3) Modify data

(1) in the SRC – > redux – > action. Js

// Expose a function, modify it, and take in a parameter that is later passed in when the page is called
export var add=(num) = >{// This is add
    //retrn Displays an object that contains the name and data of the operation
    return {type:"ADD".data:num}
}
export var del=(num) = >{// This is delete
    //retrn Displays an object that contains the name and data of the operation
    return {type:"DEL".data:num}
}
Copy the code

SRC — >redux — >reduce.js add judgment and call action.js to modify the data

// Create data
var obj={
    name:"Xiao Ming".age:22
}
// Exposure in ES6; (Data must have two parameters, using the default values of the parameters in ES6)
export function data(state=obj.age,action){// Action to invoke the modified mode
    // There will be a lot of changes later on. Action.type determines which changes to make
    switch(action.type){// Type is the type (meaning what type do you modify)
        //tian adds the operation to modify the data
        case "ADD":
            console.log(state+action.data);
            return state+action.data;
            break;
        case "DEL":
            console.log(state-action.data);
            return state-action.data;
            break;
        default:
            return state;// Return the result
            break; }}Copy the code

Note: a, import * as action asterisk is a match that matches all the exposed functions of export function in this action. B, also want to monitor in the page; C, at the time of the call, must add the modified listener, responsible for the page or component without adding data will not change.

import React, { Component } from 'react';
// Let's put them in the second positive number
import {store} from '.. /redux/store'
// Introduce everything in the action. Chu uses dispath
import * as action from '.. /redux/action';


export default class redux extends Component {
    constructor(props){
        super(props);
        this.state={
            text:store.getState()
        }
    }
    componentWillMount(){
        / / to monitor
        store.subscribe(() = >{
            // Modify the operation
            this.setState({
                text:store.getState()
            })
        })
    }
    render() {
        return (
            <div>
                <h1>Rudex</h1>{this. State. The text} {/ * * / modify data} {/ * click add operation execution, and add 1, and preach a give num * /}<button onClick={()= >{store. Dispatch (action. The add (1))}} > I + 1 point</button>
                <button onClick={()= >{store. Dispatch (action. Del (1))}} > I - 1</button>
            </div>)}}Copy the code

4) Redux data request. Data request is made in the component and then sent to Redux

(1) story – > reducer. Js

var obj={
    name:"Xiao Ming".age:22
}

export function data(state=obj,action){
    switch(action.type){
        default:
            return state;
            break; }}Copy the code

② Expose redux — >store.js

import {createStore} from 'redux';

import {data} from './reducer';

export var store = createStore(data);
Copy the code

(3) Request data from component A and send it to Redux

import React, { Component } from 'react';
import axios from "axios";
// 1. Use redux
import {store} from '.. /.. /redux/store';
import * as action from '.. /.. /redux/action';


export default class whole extends Component {
    constructor(props){
        super(props);
        this.state={
            dataone:"".// 2. Use redux to receive test data
            text:store.getState()
        }
    }
    // Get the event source of the click event, and get the value in value
    funa=(e) = >{
        console.log(e.target.value);
        this.setState({
            dataone:e.target.value
        })
    }

    componentWillMount(){
        //console.log(this.state.text);
        axios({
            url:'/paging/one'.method:'get'
        }).then((ok) = >{
            console.log(ok);
            // This is sending datastore.dispatch(action.add(ok)); })}render() {
        return (
            <div>
                <div>
                    <button value="a">all</button>
                    <p>3.redux</p>
                    {/* {this.state.text} */}
                </div>
            </div>)}}Copy the code

(4) in the story – > action. Js

export var add=(num) = >{// This function is automatically called in the A component
    return {type:'EEL'.data:num}
}
Copy the code

(5) story – > reducer. Js

var obj={
    name:"Xiao Ming".age:22
}

export function data(state=obj,action){
    switch(action.type){
        case 'EEL':
            console.log(action.data);
            return action.data;// It overwrites the data in obj, but does not change the original data
        default:
            return state;
            break; }}Copy the code

⑥ Receive and use in component B

import React, { Component } from 'react';
import { store } from '.. /redux/store';
export default class Mine extends Component {
    constructor(props){
        super(props);
        this.state={
            lala:store.getState()
        }
    }
    componentWillMount(){
       /* In this case, adding a listener will cause a memory leak and an error will be reported; But when your data is changing all the time, you have to listen to it; For example, when the filter button is clicked, this piece is clicked once and the data is modified once, so be sure to listen for changes in the data, otherwise it is always the initial value */
        // store.subscribe(()=>{
        // this.setState({
        // lala:store.getState()
        / /})
        // })
        console.log(this.state.lala);
    }
    render() {
        return (
            <div>
               
            </div>)}}Copy the code

8. Use of redux plug-in

1) Google Plugin store download:

Redux DevTools

Note: After installation, if you do not see Redux in the console, please close the browser and open it again.

2) This plugin needs to install dependencies in the project

npm install redux-devtools-extension --save-dev
Copy the code

3) use

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
// Redux hint
import logger from "redux-logger";
import thunk from "redux-thunk";
import { composeWithDevTools } from 'redux-devtools-extension';
import { createStore, applyMiddleware } from "redux";
import { Provider } from "react-redux";
// To the west is the Redux file manager
import rootReduce from "./reducers/index.js";

const store = createStore(rootReduce, composeWithDevTools(applyMiddleware(logger, thunk)));

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>.document.getElementById('root'));
Copy the code

Introduction of UI components

1.AntdUIThe use of

1) Download NPM install antd –save 2) Introduce styles in app.css

@import '~antd/dist/antd.css';
Copy the code

Note:

It can also be introduced in index.js:

import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
Copy the code

3) References in components or pages

import{tag name}from 'antd';
Copy the code

2. Load on demand

1) Manual

To introduce directly into a page or component:

import './App.css';
import { Button } from 'antd';
import "antd/es/button/style/css";
function App() {
    return (
        <div className="App">
            <Button>222222</Button>
        </div>
    );
}

export default App;

Copy the code

2) Automatic loading

First of all, the React Webpack configuration is exposed. The operation is irreversible, and it is recommended to operate after the project is created.

npm run eject
Copy the code

② Installing plug-ins

npm install babel-plugin-import --save-dev
Copy the code

(3) Add the following code to Babel in package.json:

  "babel": {
    "presets": [
      "react-app"]."plugins": [["import",
        {
          "libraryName": "antd"."libraryDirectory": "es"."style": "css"}}]].Copy the code

10. Data processing

1. Request data from the background and filter the required data according to different fields returned by different backend (take year as an example)

import React, { Component } from 'react'
import axios from "axios";
export default class whole extends Component {    
	constructor(props){        	
	super(props);        
		this.state={            
			list: []}}componentWillMount(){        
		axios({            
			url:'/paging/one'.method:'get'        
		}).then((ok) = >{            
			console.log(ok.data.datalist);            
			this.setState({                
				list:ok.data.datalist            
			})        
		})    
	}    
	ck20(e) {        
		// Request data for each click
		axios({            
			url:'/paging/one'.method:'get'        
		}).then((ok) = >{            
			console.log(ok.data.datalist);            
			// Define an empty array
			let arr = [];            
			// Loop through the original array
			for(let i=0; i<ok.data.datalist.length; i++) {// If the convenience comes out of the year is identical to click the event passed parameter
				if(ok.data.datalist[i].year===e) {                    
					// Push equal to arr and assign it to list
					arr.push(ok.data.datalist[i])                    
					this.setState({                        
						list:arr                    
					})                
				}            
			}        
		})    
	}    
	render() {        
		return (            
			<div>               
				<button value="a">all</Radio.Button>               
				<button value="a" onClick={()= >{this. Ck20 (2020)}} > 2020</button>
				<button value="b" onClick={()= >{this. Ck20 (2019)}} > 2019</button>
				<button value="c" onClick={()= >{this. Ck20 (2018)}} > 2018</button>
			</div>)}}Copy the code

2. Page jump, pass parameters, jump from list page to details page

1) list page

<Link to={{pathname:'path'.query: {id</Link> </Link>Copy the code

2) Receive on the details page

    componentWillMount(){
        const {location}=this.props;
        let recvParam;
        if(location.query&&location.query.id){// Determine if there is an argument
            recvParam=location.query.id;
            sessionStorage.setItem('data',recvParam);// Save to sessionStorage
        }else{
            recvParam=sessionStorage.getItem('data');// When state has no parameter, take the parameter in sessionStorage
        }
        console.log(recvParam);
    }
Copy the code

3) You can also filter the data to be displayed on the detail page according to the ID

3. Data filtering

(Similar to the display of goods according to conditions in Taobao, this is generally done by the background. Without clicking the classification button once, a data is sent to the background, and then the data is accepted for display)

import React, { Component } from 'react'

import axios from "axios";
export default class whole extends Component {
    constructor(props){
        super(props);
        this.state={
            dataone:""}}// Get the event source of the click event, and get the value in value
    funa=(e) = >{
        console.log(e.target.value);
        this.setState({
            dataone:e.target.value
        })
    }
    componentWillMount(){
        axios({
            url:'/paging/one'.method:'get'
        }).then((ok) = >{
            console.log(ok.data.datalist);
            this.setState({
                list:ok.data.datalist
            })            
        })
    }

    ck20(e) {
        axios({
            url:'/paging/one'.method:'get'
        }).then((ok) = >{
            console.log(ok.data.datalist);
            let arr = []
            for(let i=0; i<ok.data.datalist.length; i++) {if(ok.data.datalist[i].year === e) {
                    arr.push(ok.data.datalist[i])
                    this.setState({
                        list:arr
                    })
                }
            }
        })
    }

    render() {
        return(<div> <button value="1" onClick={()=>{this.ck20(2020)}}>2020 <button> <button value="2" The onClick = {() = > {this. Ck20 (2019)}} > 2019 < button > < / div >)}}Copy the code

11. Introduction of Iconfont

1. First, enter the official website of Ali vector icon, add the required icon to the project, and then download to the local;

2, font class reference

1) First open the.html file in the downloaded folder; 2) Introduce the first step in the index. HTML file in the public static file resource;3) Drag the iconfont. CSS from the downloaded folder into the public folder; 4) Use it directly in components or pages.

<span class="Iconfont icon- name of the corresponding icon"></span>
Copy the code

3, Symbol reference

1) First open the.html file in the downloaded folder; 2) Introduce the first step in the index. HTML file in the public static file resource;3) Drag the iconfont. Js from the downloaded folder into the public folder; 4) Add generic CSS code (just once), usually in the global app.css style; 5) in the component or page, use directly (but remove xlink :).

<svg class="icon" aria-hidden="true">
  <use href="#icon- class name of the icon"></use>
</svg>
Copy the code

4. Align the iconfont icon with the center line of the text and use

    vertical-align:middle;
Copy the code

Go back to the top and follow the ads on both sides

1. Back to the top

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Word-wrap: break-word! Important; "> < img style =" text-align: center; text-align: center; text-align: center; <p>1111111111111 </p>...... < span style =" box-sizing: border-box! Important; word-wrap: break-word! Important; word-wrap: break-word! Important; word-wrap: break-word! Important;" Window. Onscroll = function () {/ / compatibility The vertical scroll bar move distance isTop = document. The body. The scrollTop | | document. The documentElement. ScrollTop;  console.log(isTop); } function fun(){ document.body.scrollTop = document.documentElement.scrollTop = 0; } </script>Copy the code

2. Follow advertisements on both sides

<! DOCTYPE html><html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        img{
            position: absolute;
            left:0;
            top:50px;
        }
        #demo{
            width:1000px;
            margin:0 auto;
        }
    </style>
</head>
<body>
    <img src="Picture Address" alt="" id="pic"/>
    <div id="demo">
       <p>King covered tiger, chicken braised mushroom</p>. .<p>King covered tiger, chicken braised mushroom</p>
    </div>
</body>
</html>
<script type="text/javascript">
    var oPic = document.querySelector("#pic");
    window.onscroll = function(){
        // Get the page roll distance
        var sTop = document.documentElement.scrollTop || document.body.scrollTop;
        startMove( oPic  , 50 + sTop );
    }
    var timer = null;
    function startMove(obj,target){
        clearInterval(timer);
        timer = setInterval(function(){
            // Buffering motion principle
            var speed = (target-obj.offsetTop)/10;
            speed =  speed>0 ? Math.ceil(speed) : Math.floor(speed);
            if( obj.offsetTop == target ){
                clearInterval( timer );
            }else{
                obj.style.top = obj.offsetTop + speed + "px"; }},30)}</script>
Copy the code

3. A dialog box is displayed

1) index. The CSS

#teacher{
    height:200px;
    width:200px;
    background-color: aqua;
    position: absolute;
    display: none;
}
Copy the code

2) index.jsx (this popup is centered horizontally and vertically)

import React, { Component } from 'react'
import './index.css';
export default class login extends Component {    
	constructor(props){        
	super(props);        
		this.state={                    
		
		}    
	}    
	teach=() = >{        
		let teacher = document.getElementById('teacher');        
		teacher.style.display='block';        
		teacher.style.left=window.innerWidth/2 - teacher.offsetWidth/2 + 'px';
		teacher.style.top=window.innerHeight/2 - teacher.offsetHeight/2 + 'px';        
		// Call the function of the button
		this.creatBtn();    
	}    
	// Create button, close it out of the box
	creatBtn(){        
		let teacher = document.getElementById('teacher');        
		let btnDiv = null;        
		// Create a button (give an empty one, or define it in state)
		btnDiv = document.createElement("button");        
		btnDiv.innerHTML=The '*';        
		btnDiv.style.width='50px';        
		btnDiv.style.height='50px';        
		// Give the button a position
		btnDiv.style.position='absolute';        
		// Add a button to teacher
		teacher.appendChild(btnDiv);        
		// Determine the location of the button
		btnDiv.style.left = teacher.offsetWidth - btnDiv.offsetWidth + 'px';        
		// Click the button to close the popup. (You can also add a button to close the popup.)
		btnDiv.addEventListener('click'.function() {
		 	// Add events to the DYNAMICALLY created DOM
		 	teacher.style.display='none'; })}render() {        
		return (            
			<div>                
				<button onClick={this.teach}>The teacher registration</button>                
					<div id='teacher'>                                    
					</div>            

					</div>)}}Copy the code

4. Progress bar

<! doctype html><html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css" >
    #box{
        width: 200px;
        height: 30px;
        border: 1px solid black;
    }
    #jinDuBox{
        width: 0px;
        height: 100%;
        background-color: skyblue;
        text-align: center;
    }
</style>
</head>
<body style="height: 1000px">
    <div id="box">
        <div id="jinDuBox">


        </div>
    </div>
    <input type="button" value="Leave you" onclick="testf()" />
</body>
</html>


<script type="text/javascript">
var width =0; // Save the current width


function testf(){
   var myTimer = setInterval(function(){
        width+=2;
        if(width>=200){
            width = 200;
            window.clearInterval(myTimer);
        }
        $("jinDuBox").style.width = width+"px";
        $("jinDuBox").innerHTML = parseInt(width/200*100) +"%";
   },100);
}


function $(id){
    return document.getElementById(id);
}
</script>
Copy the code

Xiii. Reactlesstheuse

1. Download:

NPM install less less-loader --save-dev or yarn add less less-loader --save-dev;Copy the code

2, run,

NPM run eject to expose the webpack configuration file, you’ll find more folders named config; Git add. -m “init” -m “git” -m “git” -m “git” -m “git” -m “git”

Config — >webpack.config.js

1) Add less configuration

// Add less configuration
const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;
Copy the code

2) The lessOptions parameter is used to add items

lessOptions,
Copy the code

      // Add Less configuration
      {
        loader: require.resolve('less-loader'),
        options: lessOptions,
      },
Copy the code

3) Configuration of less

            // Less configuration
            // Add less configuration
            {
              test: lessRegex,
              exclude: lessModuleRegex,
              use: getStyleLoaders(
              {
                  importLoaders: 2.sourceMap: isEnvProduction && shouldUseSourceMap,
              },
              'less-loader'
              ),
              sideEffects: true}, {test: lessModuleRegex,
              use: getStyleLoaders(
              {
                  importLoaders: 2.sourceMap: isEnvProduction && shouldUseSourceMap,
                  modules: true.getLocalIdent: getCSSModuleLocalIdent,
              },
              'less-loader'),},Copy the code

4. Restart the project

NPM start

5. Use of less

less.bootcss.com/

Xiv. Registration

1, click 👀 to control the password display and display the black dot, click the button to get the content of the input box;

import React, { Component } from 'react';

export default class log extends Component {
    // If the component passes this value when it is not in use, an error will be reported
    // static propTypes = {
    // prop: PropTypes
    // }
    constructor(props){
        super(props);
        this.xiaoming=React.createRef();
        this.state={
            types:"password".text:'password'
           
        }
    }
    handleOk = () = > {
        console.log(this.xiaoming.current.value);
    }

    tap=() = >{
        if(this.state.types=='password') {this.setState({
                types:'text'.text:"Clear"})}else{
            this.setState({
                types:'password'.text:"Ciphertext"}}})render() {
        return (
            <div>
                <input type={this.state.types} placeholder="Password" ref={this.xiaoming} />
                <button onClick={this.tap}>dian</button>
                
                <Button onClick={this.handleOk}>Click on it to get the content of the input box above</Button>  
            </div>)}}Copy the code

2. Judge the page, no login, not allowed to enter this page

Insert a code slice hereCopy the code

3. Verify the mobile phone number and send the verification code

import React, { Component } from 'react'
import "./logon.css";
import Linkage from ".. /linkage/linkage"
export default class logon extends Component {
    constructor(props){
        super(props);
        / / cell phone number
        this.cell_phone=React.createRef();
        / / verification code
        this.verification_number=React.createRef();

        this.state={
            / / button
            click:null.// The countdown time
            hour:' '}}// Count down 60 seconds;
    time=() = >{
        // In this section, first get the phone number, then determine the phone number, when the format of the phone number is not or not, give a hint

        let phone=this.cell_phone.current.value;
        // The mobile phone number is regular
        if(! (/^1[3456789]\d{9}$/.test(phone))){ 
            alert("Wrong cell phone number, please fill it in again.");  
            // Leave the input box of the phone number blank
            this.cell_phone.current.value=' '
            return false; 
        }else{
            console.log(phone);
        }
        let  hour = 60;
        let timeClick;
        timeClick=setInterval(() = >{
            hour  --;
            this.setState({
                hour: hour,
                // When it is less than 60 seconds, give the button a stop click event
                click:'disabled'
            })
            // If less than zero, clear the timer
            if(hour===0) {// Clear the timer
                clearInterval(timeClick);
                this.setState({
                    click:null})}},1000)}render() {
        // Give this block a second count
        let newhtml=' ';
        if(this.state.hour ! =' '){
            newhtml = this.state.hour + Resend after's '
        }else if(this.state.hour===0){
            newhtml = 'Please retrieve'
        }else{
            newhtml = ' '
        }
        return (
            <div>
            	<p>Mobile phone no. :<input type="text" ref={this.cell_phone} />
                    <button type="submit" onClick={this.time} disabled={click} >Get verification code</button>
                </p>{/* the writer's machine number is incorrect */}<p>Verification code:<input type="text" ref={this.verification_number} />
                    <i className="after">{newhtml}</i>
                </p> 
            </div>)}}Copy the code

4. Let the cursor enter the input box automatically when the page is loaded or otherwise

import React, { Component } from 'react'
export default class foot extends Component {
    // The component is called after rendering (where data requests are usually written)
    componentDidMount(){
        this.input.focus();
    }
    render() {
        return (
            <div>
               <input type="text" ref={(input)= > this.input = input} />
            </div>)}}Copy the code

15 and withRouter

WithRouter higher-order component, also called: HOC; The parameter is a component and what is returned is a component. Zhe components are called high-level components. The component that is not a route switching component also has the three properties of the route switching component (Location Match History).

Sixteen, the page pass parameter

1. Page A or component sends data and page B receives it

1) A sends data

<Link to={{pathname:'/',query:{id:"Data to send"}}}> Send data </Link>Copy the code

2) Receive on page B

 // Solve the problem of data loss on the refresh page
 componentWillMount(){
        // console.log(this.props.location.query.id);
        const {location} = this.props;
        // Hot news
        let hotNews;
        if(location.query && location.query.id){
            hotNews=location.query.id;
            // Save to sessionStorage
            sessionStorage.setItem("hotNewsId",hotNews)
        }else{
        	// Remove from sessionStorage
            hotNews=sessionStorage.getItem("hotNewsId")
        }
        console.log(hotNews);
    }
Copy the code

2. Jump from page A to page B, and send data in the components of page A.

1) In page A

import React, { Component } from 'react'
import Match from '.. /components/ component name ';
export default class Notice extends Component {
    render() {
        return (
            <div>< component name history={this.props. History} />
            </div>
        )
    }
}
Copy the code

Note: if you do not write this in the parent, it will report an undefined push error. 2) In the component of page A

import React, { Component } from 'react'
export default class Notice extends Component {
   search=() = >{
      / / the refs
      this.props.history.push({
        pathname:"/".// Can send variables, strings, etc
        query: {id: The data to send}}); }render() {
        return (
            <div>
                <button type="submit" onClick={this.fun}>Click on the</button>
            </div>)}}Copy the code

3) Receive in page B

    componentWillMount(){
        console.log(this.props.location.query.id);
    }
Copy the code

Note: It will also refresh data loss, the solution is as above, the idea is that it passed data, stored in sessionStorage, when the refresh page, from the sessionStorage.

3. Multiple data transmission

1) Send data on page A

import React, { Component } from 'react'
export default class screen extends Component {
    fun=() = >{
        console.log("aaaaaaaa");
        / / the refs
        this.props.history.push({
          pathname:"/particulars".query: {XXX: {title:"Uh-huh, uh-huh.".text:"Ha ha ha ha"}}})}render() {
        return (
            <div>
     			<button type="submit" onClick={this.fun}>search</button>
            </div>)}}Copy the code

2) Receive on page B

import React, { Component } from 'react'
export default class particulars extends Component {
    constructor(props){
        super(props);
        this.state={
            data: []}}// Solve the problem of data loss on the refresh page
    componentWillMount(){
        // console.log(this.props.location.query.particularsid);
        const {location} = this.props;
        Particularsid works show
        let recvParam;
        if(location.query && location.query.XXX){
            recvParam = location.query.XXX;
            // Save to sessionStorage
            sessionStorage.setItem("XXX".JSON.stringify(recvParam));
        }else{
            // Remove from sessionStorage
            recvParam=JSON.parse(sessionStorage.getItem("XXX"));
        }
        console.log(recvParam);
        this.setState({
            // Search data from the list page
            data:recvParam
        })
    }

    render() {
        return (
            <div>
                <div className="">{data.title} {*</div>
            </div>)}}Copy the code

React link to qr code, insert video

1. Link to QR code

1) download NPM install qrcode.react –save

import React, { Component } from 'react'
import QRCode  from 'qrcode.react';
export default class Presentation extends Component {
constructor(props){
      super(props);
      this.state={
          qrUrl:'Link address'}}render() {
        return (
            <div>
               <QRCode
			       value={this.state.qrUrl}  //valueParameter is the link that generates the QR codesize={200}// The width and height of qr codefgColor="red"// Color of qr code />
            </div>)}}Copy the code

Note: To change the style, just add the class name.

2,Insert the video

1) Download NPM install — save video-react 2) Import {Player} from ‘video-react’; import “.. /node_modules/video-react/dist/video-react.css”; // This is the absolute path 3) used

import React, { Component } from 'react'
import { Player } from 'video-react';
import ".. /.. /node_modules/video-react/dist/video-react.css";
export default class Index extends Component {
    render() {
        return (
            <div>
                <Player ref="player" videoId="video-1" fluid={true} >
                    <source src="https://blz-videos.nosdn.127.net/1/OverWatch/AnimatedShots/Overwatch_AnimatedShot_Soldier76_Hero.mp4" />
                </Player>
            </div>)}}Copy the code

Note: For changes to various properties, see the linked documentation.

3. Use of picture-in-picture in video (original)

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Word-wrap: break-word! Important; "> < span style = "box-sizing: border-box; width:350px; } </style> </head> <body> <video id="video" src="https://blz-videos.nosdn.127.net/1/OverWatch/AnimatedShots/Overwatch_AnimatedShot_Soldier76_Hero.mp4" controls Playsinline loop class="box"></video> <input type="button" id="pipBtn" value=" </body> </ HTML >< script> let pipBtn=document.getElementById("pipBtn"); var pipWindow; Pipbtn.addeventlistener ('click', function(event) {console.log(' switch picture-in-picture mode... '); This. disabled = true; this.disabled = true; try { if (video ! = = document. PictureInPictureElement) {/ / try to enter the video picture in picture mode, requestPictureInPicture (); } else {/ / exit picture in picture document. ExitPictureInPicture (); } } catch(error) { console.log('&gt; Make a mistake! ' + error); } finally { this.disabled = false; }}); // Click the toggle button to trigger picture-in-picture mode, // In some browsers, the right click can also be toggled, and even automatically enter picture-in-picture mode // Therefore, Some state-related processing requires execution of video.addeventListener (' enterPictureinpicture ', function(event) {console.log(' >; The video has entered picture-in-picture mode '); Pipbtn. value = pipbtn.value. Replace (' enter ', 'exit '); pipWindow = event.pictureInPictureWindow; console.log('&gt; Video window size: '+ pipwindow.width +' x '+ pipwindow.height); / / add the resize event, everything is in order to test the API pipWindow addEventListener (' resize, onPipWindowResize); }); Video.addeventlistener ('leavepictureinpicture', function(event) {console.log('&gt; The video has left picture-in-picture mode '); Pipbtn. value = pipbtn.value. Replace (' exit ', 'enter '); / / remove the resize event pipWindow. RemoveEventListener (' resize, onPipWindowResize); }); Var onPipWindowResize = function (event) {console.log(' >; Change the window size to: '+ pipwindow.width +' x '+ pipwindow.height); } /* Feature detection */ if ('pictureInPictureEnabled' in document == false) {console.log(' Current browser does not support pictureInPictureEnabled. '); togglePipButton.disabled = true; } </script>Copy the code

Content from the form element

1. The value in the drop – down box of

import React, { Component } from 'react';
export default class nav extends Component {
	fun=(e)=>{
		console.log(e.target.value);
	}
    render() {
        return (
            <div>
            	<select name="" id="" onChange={this.fun}>
                     <option value="一"</option> <option value="二"</option> <option value="Three"</option> </select> </div>)}}Copy the code

2, use the event source to get the input box value, each print is blank solution (this is asynchronous problem)

import React, { Component } from 'react';
export default class nav extends Component {
	    constructor(props){
        super(props);
        this.state={
            text:' '
        }
    }
	fun=(e) = >{
		console.log(e.target.value);
		this.setState({
			text:e.targetvalue
		},function(){
			console.log(this.state.text); })}render() {
        return (
            <div>
            	<input type="text" onChange={this.fun} />
            </div>)}}Copy the code

3. Check the box to determine whether to check

import React from 'react';
class Text extends React.Component{
    this.Checklist=React.createRef();
    constructor(props){
        super(props);
    }
    agree=()=>{
        // Get the button first
        // console.log(this.Checklist.current);
        // True
        if(this.Checklist.current.checked===true){
            console.log('Checked')}else{
            console.log('Please check the protocol')
        }
    }
    render(){
    	// One way to write a style
        let obj={
            color:'red'
        }
        
        return <div style={obj}>
            <input type="checkbox" value="" onClick={this.agree} ref={this.checklist} /> I have read and agree to the relevant terms of Service and Privacy policy </div>}} exportdefault Text;

Copy the code

Fetch data requests, including resolution across domains

1. Fetch data request

/** * https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch * http://nodejs.cn/api/querystring.html */
import React from "react";
// This is in node
import qs from "querystring";
export default class App extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            list: []}}componentDidMount() {
        / / get request
        fetch("http://iwenwiki.com/api/blueberrypai/getIndexListening.php").then(res= > {
             return res.json();
        }).then(data= > {
            // console.log(data.listening);
            this.setState({
                list: data.listening
            })
        }).catch(err= > {
            console.log(err);
        })
        / / post request
        fetch("http://iwenwiki.com/api/blueberrypai/login.php", {method:"post".headers: {'Content-Type': 'application/x-www-form-urlencoded'."Accept":"application/json,text/plain,*/*"
            },
            {user_id:"[email protected]", password:"iwen123", verification_code:" CRFVW "} */
            // body:"[email protected]&password=iwen123&verification_code=crfvw"
            body: qs.stringify({
                user_id: "[email protected]".password:"iwen123".verification_code:"crfvw"
            })
        }).then(res= > res.json())
            .then(data= > {
                console.log(data)
            }).catch(err= > {
            console.log(err);
        })
    }
    
    render (){
        const {list} = this.state;
        return (
            <div>{/*} {list. Length > 0? list.map((item,index) => { return<p key={index}> {item.title} </p>
                        }) :
                        <div>Waiting for the</div>
                }
            </div>); }}Copy the code

2, cross-domain

1) inpackage.jsonModify the inside

Add at the end:

"proxy": "http://localhost:3000"
Copy the code

In this case, you don’t need to write http://localhost:3000 in the request, just write “http://localhost:3000”; At the same time, the configuration file has been modified.

2) Create it under SRCsetupProxy.js

NPM install http-proxy-middleware --save */
const proxy = require('http-proxy-middleware');

module.exports = function (app) {
    app.use(
        proxy.createProxyMiddleware('/api', { // / The API is a request that needs to be forwarded
            target: 'http://localhost:3100'.// Here is the interface server address
            changeOrigin: true.pathRewrite: { '^/api': ' '}}}))Copy the code

Use:

import React from "react";
export default class App extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            
        }
    }
    componentDidMount() {
        fetch("/api/list").then(data= > data.json()).then(res= >{
            console.log(res)
        }).catch(req= > {
            console.log(req);
        })
    }
    
    render (){
        return (
            <div>Solve cross-domain: https://github.com/facebook/create-react-app/blob/master/docusaurus/docs/proxying-api-requests-in-development.md#configu ring-the-proxy-manually</div>); }}Copy the code