react parameter transmission related records

Posted by bob1660 on Fri, 25 Feb 2022 11:26:43 +0100

Primary directory

Secondary directory

Tertiary directory

1, Principle related:

1. On the principle of render rendering twice

2, Question:

1. fetch request

let getFileTypesUrl = `${context.contextPath}/projectfile/getAllFileTypes?p_no=` + this.state.projectNo;
//Call method

getFileTypes(url) {
                method: "GET"
    		//Response result of background request data: the requested data, similar to ajax
            .then((response) => response.json())
            .then((data) => {
                let list = [];
                if (data !== null && data !== undefined) {
                    data.forEach((item, index, arr) => {
                        let obj = {value: item, text: item};
                    this.state.fileTypes = list;

Method 1: callback

import {ewdUrl,fnNewToken, fnNewToken2} from "./util/util";
getNewToken2() {
   let that = this
      token: Boolean(newToken) ? newToken : localStorage.getItem("jwtToken")
  // console.log('newToken===', newToken)

Method 2:

async getNewToken() {
  let newToken = await fnNewToken();
  console.log('newToken===', newToken)
    token: Boolean(newToken) ? newToken : localStorage.getItem("jwtToken")

Method 1: callback

export let fnNewToken2 = function (myfunc) {
    let newToken = '';
    let tokenURL = casUrl + "/cas/jwt/token";
    fetch(tokenURL, {
        method: 'GET',
        credentials: 'include',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded;'
    }).then(resp => resp.json()).then(resp => {
        if (resp) {
            if (resp.status === true) {
                newToken = resp.jwtToken;
                    console.log("util token", newToken)
                    localStorage.setItem("jwtToken", newToken)
            } else {
                console.log('token Verification failed')

Method 2:

export let fnNewToken = async function () {
    let tokenURL = casUrl + "/cas/jwt/token";
    let response = await fetch(tokenURL, {
        method: 'GET',
        credentials: 'include',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded;'
    let data = await response.json();
    if(Boolean(data.status) && data.status === true){
        return data.jwtToken;
    } else{
        console.log("token Verification failed!")
        return null;

2. Method

onClick: (item, events) => {    
    let previewUrl = `${context.contextPath}/projectfile/getFileInfo?fileId=` +rowData.file_id;,previewUrl);

Showmodal uses the call() method instead of declaring this in the constructor showModal = this. showModal. Bind() can write the content of this method directly.
Use this here showModal. A form like bind (this) cannot enter this method.

3. Return

  1. Return to previous url
    document. Refer: the refer property returns the URL of the source document from which the current document is loaded
    Location object method:
    assign() loads a new document
    reload() reloads the current document
    replace() replaces the current document with a new one

  2. Newly opened browser tab:, '_blank').location;

  3. Jump and ask for backstage
    window.location = ${context.contextPath}/projectpage/index?p_no=+p_no;

  4. js storage object
    JavaScript storage object
    The Web storage API provides two storage objects, sessionStorage and localStorage, to add, delete, modify and query the data of Web pages.

localStorage is used to save the data of the whole website for a long time. The saved data has no expiration time until it is manually removed.

sessionStorage is used to temporarily save the data of the same window (or tab). These data will be deleted after closing the window or tab.

Storage object method
 method							describe
key(n)						Returns the number of rows in the storage object n Name of key
getItem(keyname)			Returns the value of the specified key
setItem(keyname, value)		Add key and value. If the corresponding value exists, update the value corresponding to the key.
removeItem(keyname)			Remove key
clear()						Clear all keys in the storage object

window.localStorage		Store in browser key/value yes. There is no expiration time.
window.sessionStorage	Store in browser key/value yes. This data will be deleted after closing the window or tab.

4. sessionStorage and localStorage and cookie s


        //Judge whether it exists
        // if(!window.sessionStorage) {
            if (sessionStorage.getItem("index") != null) {
                let indexData = sessionStorage.getItem("index");

				//componentDidMount cannot use setState. setState is asynchronous. If you want to see the modified value of state immediately, you need to use the callback of setState
                this.setState({index: indexData}, () => {
                    console.log('index', this.state.index);
            else {
                this.setState({index: 0});
        // }

Save: sessionstorage setItem(“index”,index );
Take: sessionstorage getItem(“index”)
localStorage.getItem("jwtToken") removal:

Use cookie s to store user information:
session/cookie is a data storage form used to store user related information
The session is stored in the server as an object, while the cookie is stored in the browser as a string
Because session s are stored on the server, they will occupy server resources. Generally speaking, small projects use cookie s more cookie Related packages
npm install react-cookies --save

2.cookie Knowledge reserve
import cookie from 'react-cookies'

3,Save; set up cookie,The third parameter means that all pages can use this cookie,value,{path:"/"})
6,Setting failure
let inFifteenMinutes = new Date(new Date().getTime() + 24 * 3600 * 1000);//one day'userId', "123",{ expires: inFifteenMinutes });

According to the above format of accessing cookies, you can write cookies js

import cookie from 'react-cookies'

Get current user cookie
export const loginUser = () => {
  return cookie.load('userInfo')

 User login, save cookie
export const onLogin = (user) => {'userInfo', user, { path: '/' })

User logout, delete cookie
export const logout = () => {
  window.location.href = '/Login'

3. react page call

Take the student management system as an example. When the pathname is' / 'without Login (without cookie), jump to Login, and then jump to the corresponding permission page. When the pathname is' / 'after logging in (when there is cookie storage), jump to the permission main page corresponding to the current user

import React, { Component } from 'react'
import { Router, Route, Switch } from 'react-router-dom'
import { createBrowserHistory } from 'history'
import { loginUser } from './cooike' // introduce
import {
  StudentLayout, TeacherLayout, AdminLayout, Login,
} from './pages' // Import page
import NotFound from './components/Common/NotFound'
import Loading from './components/Common/Loading'

const browserHistory = createBrowserHistory() // Routing distribution

class BasicRoute extends Component {
  render () {
    const userInfo = loginUser()
    if (userInfo && window.location.pathname === '/') {
      if (userInfo.accountRole === 0) {
        window.location.href = '/Admin'
      } else if (userInfo.accountRole === 1) {
        window.location.href = '/Teacher'
      } else if (userInfo.accountRole === 2) {
        window.location.href = '/Student'
    return (
      <Router history={browserHistory}>
              ? <Route exact path="/Login" component={Login} />
              : (
                <Route path="/Student" component={StudentLayout} />
                <Route path="/Teacher" component={TeacherLayout} />
                <Route path="/Admin" component={AdminLayout} />
          <Route exact path="/" component={Loading} />
          <Route exact component={NotFound} />

export default BasicRoute

React cookie official website instance:


The user logs out and deletes the cookie

export const logout = () => {
  window.location.href = '/Login'

If not in cookie If the path is specified in the remove () method, the current account will not be completely logged out. For example, clicking the exit button under the / Admin/Personal/Add path will not log out as expected. The solution to this problem is to log out in the cookie Set the path in the remove() method

The user logs out and deletes the cookie

export const logout = () => {
  cookie.remove('userInfo', { path: '/' })
  window.location.href = '/Login'

You can solve the problem that cookie s are not cleared

5. The difference between componentWillMount and componentDidMount

About react lifecycle

The life cycle of a component can be divided into three states:

  • Mounting: real DOM inserted
  • Updating: being re rendered
  • Unmounting: removed from real DOM

Life cycle methods include:

componentWillMount is invoked before rendering and the client is also on the server side. componentDidMount :
After the first rendering, it is called only on the client side. After that, the component has generated the corresponding DOM structure, which can be accessed through this Getdomnode().
If you want to work with other JavaScript frameworks, you can call setTimeout in this method.
setInterval or send AJAX request (prevent asynchronous operation from blocking UI). componentWillReceiveProps
Called when the component receives a new prop (Updated). This method will not be called when initializing render. shouldComponentUpdate
Returns a Boolean value. Called when the component receives a new props or state. Not called during initialization or when using forceUpdate. It can be used when you confirm that you do not need to update the component.
componentWillUpdate is called when the component receives a new props or state but has not yet render ed. Is not called during initialization.
componentDidUpdate is called immediately after the component completes updating. Not called during initialization. componentWillUnmount from
Called immediately before removal from the DOM.

6. react setState understanding

7. This in react Setstate ({index: 1}) and this state. The difference between index = 1

1)this.state is usually used to initialize state, this Setstate is used to modify the state value. If you initialize state and then use this State, the previous state will be overwritten if this is used Setstate will only replace the corresponding state value.
2)this.setState({}) will trigger the render method to re render the interface. And this state. XXX = '' will not reload the UI.

3)this.setState({}) is asynchronous.

8. An error is reported when adding a token to headers

Solution: (the reason is not clear)

// Update state when props changes
componentWillUpdate(nextProps, nextState, nextContext) {
  // First compare whether the values are the same
  if (this.state.pass !== nextProps.pass) {
      pass: nextProps.pass

9. Parameter transfer of parent-child components

Pass parameters from parent component to child component:

//SpotInspector in the parent component is the name of the child component


status is the parameter name
//The child component uses props to receive the parameters passed by the parent component

constructor(props) {
    this.state = {
      status: this.props.status,

When the parent page is rendered for the first time, the status is passed to the child component,
At this time, the child component gets this set in the parent component state. The default value of status (for example, the default value is' ')
After the parent component gets the data through the interface, render the page again and pass the new value to the child component
This. In the subcomponent props. The status value changes accordingly.
However, the state in the constructor will not be updated

This. Is required when echoing this value in a sub page props. status
When the value in the parent component changes, the parameter props passed to the child component The status will also change, but the state in the subcomponent will not change.
So you need to use this when echoing in the sub page props. status

There will be an individual problem, such as this. When submitting data state. Status, but when the value of the parent component changes, the state will not be updated (at this time, the value of state is the initialization value)

The state will be updated only when the onChange method is triggered when the input box is changed. If the content of the input box is not modified, the state will not be updated. Therefore, you can compare the value in the next props (this is the new value obtained in the second rendering) with the state

// Update state when props changes
componentWillUpdate(nextProps, nextState, nextContext) {
  // First compare whether the values are the same
  if (this.state.pass !== nextProps.pass) {
      pass: nextProps.pass

Value transfer from child component to parent component:

10. The color of an item in the drop-down menu is different

onToggle={(t) => {
    if(dropdownStyle === "class2"){
        document.querySelectorAll('.class2 .epm-menu_item-title').forEach(el =>{ if (el.innerText.indexOf('item2') > -1 ){ = 'red'}})
    } else{
        document.querySelectorAll('.class1 .epm-menu_item-title').forEach(el =>{ if (el.innerText.indexOf('item2') > -1 || el.innerText.indexOf('item1') > -1){ = 'red'}})

11. The difference between function() and () = >

1) Definition

//Functions defined using function
function foo(){
// Arrow function
var obj = { aa: foo };
foo(); //Window
obj.aa() //obj { aa: foo }

2) this point
The point of this in the function defined by function changes with the change of the calling environment.
When using the arrow function, the direction of this does not change.

3) Constructor
Function can define a constructor, but arrow function can't.

4) Variable promotion
Due to the memory mechanism of js, the level of function is the highest. When using the arrow function to define the function, you need the var(let const not to mention) keyword, and the variable defined by var cannot be promoted. Therefore, the arrow function must be defined before the call!

foo(); //123
function foo(){

arrowFn(); //Uncaught TypeError: arrowFn is not a function
var arrowFn = () => {

12. Three ways of transmitting parameters in React route

Mode 1:
Via params
1. In the routing table

  <Route path=' /sort/:id '   component={Sort}></Route>

1) HTML mode

<Link to={ ' /sort/ ' + ' 2 ' }  activeClassName='active'>XXXX</Link > 

2) JS mode

this.props.history.push(  '/sort/'+'2'  )

3.sort page

   adopt        You can accept the passed parameters( id)

Mode 2:
Through query
1. Premise: parameters can only be passed if other pages jump over
Note: the routing table does not need to be configured. The contents in the routing table are as usual:
2. Link
1) HTML mode

2) JS mode

this.props.history.push({ path : '/sort' ,query : { name: ' sunny'} })

3. sort page

Mode 3:
Via state
1. It is similar to query, but the properties are different. Moreover, the parameters passed by state are encrypted, and the parameters passed by query are public, which are in the address bar
2. Link
1) HTML mode:

 <Link to={{ path : ' /sort ' , state : { name : 'sunny' }}}> 

2) JS mode:

this.props.history.push({ pathname:'/sort',state:{name : 'sunny' } })

3. sort page

13. React download table data export to generate excel file

1. Installation dependency

npm install js-export-excel

2. Introduce dependency

import ExportJsonExcel from 'js-export-excel';

3. Use

    const option = {};
    // File name
    option.fileName = 'Coal handling system report';
    // Data set of file
    option.datas = [
            // Usually used to put our tabular data
            sheetData: this.state.tableItems,
            // sheet name
            sheetName: 'sheet',
            // first line
            sheetHeader: ['Equipment name','Longitudinal tear 1','Longitudinal tear 2','Deviation trip','Speed trip','Deviation alarm','Speed alarm'],
            //The column width should correspond to the column order, and write if necessary
            // columnWidths: []

    const toExcel = new ExportJsonExcel(option);
    let file = toExcel.saveExcel()


14. Use moment to get the date

  1. Install moment dependency
    npm install moment --save

  2. Introduce moment dependency
    import moment from 'moment'

  3. use

//Get current time
moment().format('YYYY-MM-DD HH:mm:ss');   //2020-08-25 10:23:59

//Get year
moment().year();       //2020
moment().get('year');  //2020

//Get month (0: January 11: December)
moment().month();       //7
moment().get('month');  //7

//Get a day of the month
moment().date();       //25
moment().get('date');  //25

//Get hours
moment().hours();          //11
moment().get('hours');     //11

//Get minutes
moment().minutes();        //11
moment().get('minutes');   //11

//Get seconds
moment().seconds();        //17
moment().get('seconds');   //17

//Get today's day of the week
moment().format('dddd');     //Tuesday
moment().format('d');        //2

moment().day();              //2 (0 ~ 6 represent Sunday to Saturday respectively)
moment().weekday();          //2 (0 ~ 6 represent Sunday to Saturday respectively)
moment().isoWeekday();       //2 (1 ~ 7 represent Monday to Sunday respectively)
moment().get('date');        //2
moment().get('weekday');     //2
moment().get('isoWeekday');  //2

Set time

//Set Year 
moment().set('year', 2019);
moment().set({year: 2019});

//Set month
//0 ~ 11, 0: January, 11: December
moment().set('month', 8);

Format time
//Format specified time

time difference
now_time.diff(start_time,"hour");      //Hours
now_time.diff(start_time,"minute");    //Minutes
now_time.diff(start_time,"second");    //The number of seconds from the initial time
now_time.diff(start_time, 'months');   //Months
now_time.diff(start_time, 'weeks');    //Number of weeks
now_time.diff(start_time, 'days');     //Days

Relative time
//add time    
//subtract time
moment().subtract(10, 'days').format('YYYY-MM-DD HH:mm:ss');  //2020-08-15 10:51:48
moment().subtract(6, 'days').format('YYYY-MM-DD HH:mm:ss');  //2020-08-19 10:51:48
moment().subtract(3, 'days').format('YYYY-MM-DD HH:mm:ss');  //2020-08-22 10:51:48
moment().subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss');  //The day before: 2020-08-24 10:51:48
moment().format('YYYY-MM-DD HH:mm:ss');                      //Current time: 2020-08-25 10:51:48
moment().add(1, 'days').format('YYYY-MM-DD HH:mm:ss');       //The next day: 2020-08-26 10:51:48
moment().add(3, 'days').format('YYYY-MM-DD HH:mm:ss');       //2020-08-28 10:51:48
moment().add(10, 'days').format('YYYY-MM-DD HH:mm:ss');      //2020-09-04 10:51:48

moment().subtract(1, 'year').format('YYYY-MM-DD HH:mm:ss');  //Previous year:
moment().add(1, 'year').format('YYYY-MM-DD HH:mm:ss');       //The following year:

moment().subtract(1, 'hours').format('YYYY-MM-DD HH:mm:ss');  //Last hour:
moment().add(1, 'hours').format('YYYY-MM-DD HH:mm:ss');       //After one hour:

// startOf is set to the start time 
moment("20111031", "YYYYMMDD").fromNow();    //9 years ago
moment().startOf('day').fromNow();           //11 hours ago
moment().startOf('hour').fromNow();          //an hour ago
moment().endOf('day').fromNow();             //in 13 hours
moment().endOf('hour').fromNow();            //in 15 minutes

//Beginning of the year
moment().startOf('year').format('YYYY-MM-DD HH:mm:ss');   //2020-01-01 00:00:00
//At the beginning of the month
moment().startOf('month').format('YYYY-MM-DD HH:mm:ss');  //2020-08-01 00:00:00
//At the beginning of the day
moment().startOf('day').format('YYYY-MM-DD HH:mm:ss');    //2020-08-25 00:00:00
//First day of the week (Sunday)
moment().startOf('week').format('YYYY-MM-DD HH:mm:ss');   //2020-08-23 00:00:00
//Early Monday of this week
moment().startOf('isoWeek').format('YYYY-MM-DD HH:mm:ss');  //2020-08-24 00:00:00

 moment().startOf('day').format('YYYY-MM-DD HH:mm:ss') // Time format of 0:00 of the day
 moment().startOf('day').format('X') // The 0:00 time stamp of the current day is output in 10 bit Unix timestamp (seconds)
 moment().endOf('day').format('YYYY-MM-DD HH:mm:ss') // Time format of 23:59:59 of the day
 moment().endOf('day').format('x') //Output with 13 bit Unix timestamp at 23:59:59 on the same day (MS)

 moment('2020-06-30').startOf('day').format('x') // Output with 13 bit Unix timestamp at 0:00 on June 30, 2020 (MS)
 moment('2020-06-30').endOf('day').format('x') //  Output with 13 bit Unix timestamp at 24:00 on June 30, 2020 (MS)

Topics: Javascript Front-end React