react custom functions, life cycle hook function, the modified state, components, component values pass

1 Review

2, Custom Function

The first letter of the size of the event onclick ==> onClick onchange ==> onChange

  • ---- ordinary click event invokes the event without (), plus the immediate implementation
import React, { Component } from 'react';

export default class extends Component {
  constructor (props) {
    super(props);
    this.state = {
    }
  }

  test () {
    console.log('按钮被点击了')
  }

  render () {
    return (
      <div>
        <button onClick={ this.test }>按钮点击事件</button>
      </div>
    )
  }
}
  • The event object --- a custom in events of default parameters event
import React, { Component } from 'react';

export default class extends Component {
  constructor (props) {
    super(props);
    this.state = {
    }
  }

  test (event) { // ++++++++++++++++++++++++
    console.log('按钮被点击了', event)
  }

  render () {
    return (
      <div>
        <button onClick={ this.test }>按钮点击事件</button>
      </div>
    )
  }
}
  • If you want to use this event --- within the internal structure of the function to add new methods
import React, { Component } from 'react';

export default class extends Component {
  constructor (props) {
    super(props);
    // 2.给当前的实例添加一个方法,这个方法其实就是自定义的函数,给自定义的函数绑定this,就可以在自定义的函数内部访问this
    this.testfn = this.test.bind(this); 
    this.state = {
    }
  }

  test () {
    console.log('按钮被点击了', this) // 1.默认this为未定义,需要改变this指向
  }

  render () {
    return (
      <div>
        <button onClick={ this.testfn }>按钮点击事件</button>
      </div>
    )
  }
}
  • If you want to use this event within this point --- --- just change recommendation
import React, { Component } from 'react';

export default class extends Component {
  constructor (props) {
    super(props);
    this.state = {
    }
  }

  test () {
    console.log('按钮被点击了', this) // 1.默认this为未定义,需要改变this指向
  }

  render () {
    return (
      <div>
      {
        // 2、onClick={ this.test.bind(this) } --- 只是改变this指向
      }
        <button onClick={ this.test.bind(this) }>按钮点击事件</button>
      </div>
    )
  }
}
  • Mass participation event
import React, { Component } from 'react';

export default class extends Component {
  constructor (props) {
    super(props);
    this.state = {
    }
  }

  test (str) {
    console.log('按钮被点击了', this) // 1.默认this为未定义,需要改变this指向
    console.log(str)
  }

  render () {
    return (
      <div>
      {
        // 2、this.test.bind(this, '111111')
      }
        <button onClick={ this.test.bind(this, '111111') }>按钮点击事件</button>
      </div>
    )
  }
}

3 Lifecycle hook function

  • vue: create / mount / update / destroy

Stable version, part of the need to abolish the life cycle of the hook function

  • Initialization phase

    constructor () // initialization data

    componentWillMount () // old former (15 version) requests data, now basically abolished, 17 version useless

    render () // ---- essential initial data load

    componentDidMount () // request data, DOM --- is equivalent to the operation of the mounted vue

  • Runtime Phase

    componentWillReceiveProps () // monitor data, now basically abolished, 17 version useless

    shouldComponentUpdate () // returns true --- default enhance the performance of critical react

    componentWillUpdate () // now basically repealed 17 version useless

    render () // render the view to reproduce the essential ----

    componentDidUpdate () // DOM operations ----- vue is equivalent to the requested data is not recommended Updated ---

  • Destruction stage

    componentWillUnmount () // component is similar to the destruction --- vue of beforeDestroy

The new version of the life cycle

  • Initialization phase

    constructor ()

    static getDerivedStateFromProps call immediately before () // in the initial installation and subsequent updates are calling the render method. It should return to update the status of an object, or null any content is not updated. https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

    render ()

    componentDidMount ()

  • Runtime Phase

    static getDerivedStateFromProps ()

    shouldComponentUpdate ()

    render ()

    getSnapshotBeforeUpdate () // call immediately prior to submission to the DOM in recent rendered output

    componentDidUpdate ()

  • Destruction stage

    componentWillUnmount ()

  • Error Handling

    static getDerivedStateFromError()

    componentDidCatch()

4 + life cycle modification status

this.setState()

import React, { Component } from 'react';
import axios from 'axios';
export default class extends Component {
  constructor (props) {
    super(props);
    this.state = {
      prolist: []
    }
  }
  // +++++++++++++++++++++++++++++
  componentDidMount () {
    // 请求数据
    axios.get('/api/pro').then(res => {
      // 修改状态
      this.setState({
        prolist: res.data.data
      })
    })
  }

  render () {
    let { prolist } = this.state
    return (
      <div>
        {
          prolist.map(item => (
            <p key = { item.proid }> { item.proname } - { item.price } </p>
          ))
        }
      </div>
    )
  }
}

5, run the command differentiate webpack environment

cnpm i cross-env -D

  • Configuration options package.json of scripts
 "scripts": {
    "dev": "cross-env NODE_ENV=development webpack-dev-server --config webpack.config.js",
    "build": "cross-env NODE_ENV=production webpack --config webpack.config.js"
  },
  • Configuring webpack plugin plugins
const isDev = process.env.NODE_ENV =='development'

plugins: [ // 添加插件 ---- 数组
  new webpack.optimize.UglifyJsPlugin(), // 压缩js文件
  new webpack.DefinePlugin({ // ++++++++++++++++++
    'process.env': {
      NODE_ENV: isDev ? '"development"' : '"production"'
    }
  }),
  new HtmlWebPackPlugin({ // 实例化一个 html 的webpack的插件
    template: 'index.html' // 找的就是当前文件夹下的index.html文件
  })
],

6, the package data request

  • utils / request.js custom axios
// 1、引入axios模块
import axios from 'axios';

// 2、判断是什么环境 -- 开发环境 -- 生产环境
// 真  ----   开发环境 ---- 反向代理
// 假  ----   生产环境
const isDev = process.env.NODE_ENV === 'development'

// 3、自定义axios
let request = axios.create({
  // 基础的请求地址
  baseURL: isDev ? '/api' : 'http://47.92.152.70'
})

// 4、给所有的请求添加头信息
// request.defaults.headers['token'] = localStorage.getItem('token')

// 4、使用axios的拦截器  ----  请求的拦截器  +  响应的拦截器
// http://www.axios-js.com/zh-cn/docs/#%E6%8B%A6%E6%88%AA%E5%99%A8

// 添加请求拦截器
request.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  // 所有的请求都需要的字段,所有的请求添加loading效果
  // token
  config.headers['token'] = localStorage.getItem('token')
  return config;
});

// 添加响应拦截器
request.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  // 消除请求的loading效果
  return response;
});

// 5、暴露axios模块
export default request;
  • utils / api.js request to the interface package
// 1、引入自定义的axios
import request from './request';

// 2、封装接口

/**
 * 封装 数据列表的接口
 * pageCode 页面
 * limitNum 每页显示个数
 */
const getProlist = (pageCode, limitNum) => {
  pageCode = pageCode * 1 || 0;
  limitNum = limitNum * 1 || 10;
  // 使用promise解决异步问题
  return new Promise((resolve) => {
    // 因为自定义的axios包含baseUrl,此处只需要写后面的接口即可
    request.get('/pro', { params: { pageCode, limitNum} }).then(res => {
      resolve(res.data)
    })
  })
}

/**
 * 请求轮播图接口
 * type 哪一个类型的轮播图 home / kind / activity 
 */

const getBannerlist = (type) => {
  type = type || 'home';
  return new Promise((resolve) => {
    request.get('/banner', { params: { type }}).then(res => {
      resolve(res.data)
    })
  })
}

// 3、暴露接口
export {
  getProlist,
  getBannerlist
}

7 components

  • App.js parent component
import React, { Component } from 'react'
import { getBannerlist, getProlist } from '@/utils/api';
import Prolist from './Prolist'; // +++++++++++++++++++++++++++++
export default class extends Component {
  constructor (props) {
    super(props);
    this.state = {
      bannerlist: [],
      prolist: []
    }
  }

  componentDidMount () {
    getBannerlist().then(data => {
      this.setState({
        bannerlist: data.data
      })
    })
    getProlist().then(data => {
      this.setState({
        prolist: data.data
      })
    })
  }

  render () {
    return (
      <div>
        <ul>
          { this.state.bannerlist.map(item => (
            <li key={item.bannerid }>{ item.img }</li>
          ))}
        </ul>
        { 
          // +++++++++++++++++++++++++++++++++++
        }
        <Prolist />
      </div>
    )
  }
}
  • ------ Prolist.js subassembly is in the inner row jsx follow js style writing style, plus react the {}
import React, { Component } from 'react';

export default class extends Component {
  render () {
    return (
      <ul>
        <li>
          {
            // <img src="" alt="" style="width: 60px;"/>
          }
          <img src="" alt="" style={ { width: '60px'} }/>
          <p>华为meta 30</p>
          <p>5999</p>
        </li>
      </ul>
    )
  }
}

8 parent component subassembly to pass values

App.js parent component sub-assemblies Prolist.js

  • Parent component subassembly to pass values

Where parent component subassembly call, add a custom attribute, the attribute value is a value to pass to the sub-assembly, if the value of the variable is passed, boolean, number type, the need to react {}

<Prolist prolist={ this.state.prolist }/>

In sub-assemblies can be accessed by this.props to data passed to the parent component sub-assemblies, where you get depends on where the data using the data, rendering data subcomponents

import React, { Component } from 'react';

export default class extends Component {
  render () {
    console.log(this.props)
    return (
      <ul>
        {
          this.props.prolist.map(item => (
            <li key={item.proid}>
              <img src={  item.proimg  } alt="" style={ { width: '60px'} }/>
              <p>{ item.proname }</p>
              <p>{ item.price }</p>
            </li>
          ))
        }
      </ul>
    )
  }
}

If the need to verify the data type of data transmitted parent component

After checking react15.5 type in the third module of the prop-types

cnpm i prop-types -S

Verifying the data type of subassembly components

bool, array, func, number, object, string symbol, node, element

import React, { Component } from 'react';
import PropTypes from 'prop-types'; // ++++++++++++++++++++++
class Com extends Component {
  render () {
    console.log(this.props)
    return (
      <ul>
        {
          /*
          <li>
          {
            // <img src="" alt="" style="width: 60px;"/>
          }
          <img src="" alt="" style={ { width: '60px'} }/>
          <p>华为meta 30</p>
          <p>5999</p>
        </li>
        */
        }
        {
          this.props.prolist.map(item => (
            <li key={item.proid}>
              <img src={  item.proimg  } alt="" style={ { width: '60px'} }/>
              <p>{ item.proname }</p>
              <p>{ item.price }</p>
            </li>
          ))
        }
      </ul>
    )
  }
}
// +++++++++++++++++++
Com.propTypes = {
  prolist: PropTypes.array
}

export default Com

9, to the parent component subassembly pass value

Parent component sub-assemblies to traditional values, is actually the parent component sub-assemblies to pass the custom properties, the value of this property is a function, the function definition of parent component, subassembly call this function, we must remember that this points to a problem

Subassembly

import React, { Component } from 'react';

// class Com extends Component {
//   sendData () { // ++++++++++++++
//     console.log(this.props) // 记得改变this指向,{fn: function()}
//     this.props.fn('我是子组件')
//   }

//   render () {
//     return (
//       <div>
//         <button onClick={ this.sendData.bind(this) }>给父组件传值</button>
//       </div>
//     )
//   }
// }

class Com extends Component {
  render () {
    return (
      <div>
        <button onClick={ () => {
          // +++++++++++++++++++++++
          this.props.fn('222222222222')
        } }>给父组件传值</button>
      </div>
    )
  }
}

export default Com;

Parent component

import React, { Component } from 'react'
import Child from './Child';
export default class extends Component {
  constructor (props) {
    super(props);
    this.state = {
    }
  }

  getData (str) { // +++++++++++++++++++++++++++
    console.log(str)
  }

  render () {
    return (
      <div>
        {
          // ++++++++++++++++++++++ fn 
        }
        <Child fn={ this.getData.bind(this) }/>
      </div>
    )
  }
}

10, react scaffolding

create-react-app

  • 1, install scaffolding

    cnpm i create-react-app -g

    create-react-app myapp

  • 2, do not install scaffolding npx ---- node 8.9 above automatically have

    npx create-react-app myapp

  • 3, using dva create react project --- dva / cli

    cnpm install dva-cli -g

    dva new myapp

Guess you like

Origin www.cnblogs.com/hy96/p/11891133.html