20200129-React basis - Advanced Applications

First, the combination of inheritance

  1. Concept: The contents of the tag assembly between open and closed assembly inside the tag display on display, by passing prop. (Parent components define the content of the sub-assembly, similar to the slot vue slot)
  2. form
  • Inclusion relation
  • Rendering Other components
//父组件
import ChildA from './childA.jsx'

class Father extends Component {
    state = {}
    render(){
        let Acom = <a href="#">这是一个a标签组件</a>
        return <div className="extend-father" style={{border:'1px solid #000'}}>
            father content
            <ChildA Acom={Acom}>
                <h1>包含关系:嵌入内容</h1>
            </ChildA>

        </div>
    }
}
// 子组件
class ChildA extends Component {
    constructor(props){
        super(props)
        this.state = {}
    }
    render(){
        return <div style={{backgroundColor:'orange'}}>
            hello world!
            {/* 包含关系 */}
            {this.props.children}
            {/* 渲染其他组件 */}
            {this.props.Acom}
        </div>
    }
}

Second, the error handling border

  1. Concept: Error border is actually a component that can capture and print the javascript error occurred in its subcomponents tree anywhere, and he will render spare ui.
  2. deal with
  • Static getDerivedStateFromError () // Render standby ui
  • componentDidCatch () // print an error message
  1. Note: The following error can not be captured
  • Event Processing
  • Asynchronous code
  • Side rendering service
  • Thrown out its own mistakes
  1. use
//错误边界组件
class ErrorBoundary extends Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false };
    }

    static getDerivedStateFromError(error) {
        // 更新 state 使下一次渲染能够显示降级后的 UI
        return { hasError: true };
        
    }

    componentDidCatch(error, info) {
        // 你同样可以将错误日志上报给服务器
        console.log(error, info)
    }

    render() {
        if (this.state.hasError) {
            return <h1>Something went wrong.</h1>;
        }
        return this.props.children;
    }
}

// 父组件
// Error是想要显示的组件,ErrorBoundary是错误边界组件,如果有错,那么就不会渲染Error组件
render() {
  return <ErrorBoundary>
    <Error />
  </ErrorBoundary>
}

Third, the high-order component applications

  1. Concept: high-order component (HOC) is a logic component reuse react in advanced technology, but not the higher-order component itself React API, which is only a model that is produced by a combination of properties itself react inevitable .
  2. effect
  • Public extract business logic, taking
  • Rendering hijacking
  1. Use: passing a higher-order function component, a new component returns after treatment
  2. Precautions
  • You can not change the original component
  • Do not use the render method HOC
  • refs not transmitted (React.forwardRef)

// 渲染一个列表,使用hoc分离数据请求和渲染。思路:将请求数据封装成一个高阶组件,将排序也封装成一个高阶组件,然后渲染组件作为参数传递给高阶组件
/*渲染组件*/
import HocSortList from './hocSortList.jsx'

class List extends Component {
    constructor(props){
        super(props)
        this.state = {}
    }
   render(){
        return <div className="list">
            <ul>
                {this.props.list.map((item,index) => <li key={index}>{item.name}---{item.age}</li>)}
            </ul>
        </div>
   }
}
export default HocGetData(HocSortList(List))
/*请求数据高阶组件*/
function HocGetData(Com){
    return class extends Component{
        constructor(props){
            super(props)
            this.state = {
                loading:true,
                list:[]
            }
        }
        componentDidMount(){
            setTimeout(()=>{
                this.setState({
                    list:[
                        {name:'xm',age:18},
                        {name:'xh',age:19},
                        {name:'xl',age:17},
                        {name:'xx',age:9},
                    ],
                    loading:false
                })
            },3000)
        }
        render(){
            return this.state.loading ? <p>正在加载...</p>:<Com list={this.state.list}/>
        }
    }
}
export default HocGetData
/*排序高阶组件*/
function HocSortList(Com){
    return class extends Component {
        constructor(props){
            super(props)
            this.state = {
                list:[...props.list]
            }
            this.state.list.sort((a,b)=>{
                return a.age - b.age
            })
        }
        render(){
            return <Com list={this.state.list} />
        }
    }
}

export default HocSortList

四、Refs and the Dom

  1. Scenarios
  • Focus, select the text or media player
  • Animation or animation library requires third-party operating dom
  1. use
  • () To create a ref by React.creatRef
  • Dom by current property acquisition
  1. Precautions
  • Try not to be exposed to the ref parent component
  • Component is bound to a class ref acquired are instances of classes, component binding to the function being given ref, so derived following a
  • It can only be used in class class assembly. (Internal function components can be used, do not understand wrong)
import React , {Component , useEffect} from 'react'
/*类组件*/
class RefCom extends Component {
    constructor(props){
        super(props)
        this.state = {
            inpRef : React.createRef()
        }
    }
    componentDidMount(){
        console.log(this.state.inpRef);
        this.state.inpRef.current.focus()
    }
   render(){
        return <div>
            <p>类组件中的dom操作</p>
            <input type="text" ref={this.state.inpRef}/>
        </div>
   }
}
/*函数组件*/
// function RefCom(){
//     let inpRef = React.createRef()
//     useEffect(() => {
//         console.log(inpRef.current);
//         inpRef.current.focus()
//     },[])
//     return <div>
//         <p>函数组件中的dom操作</p>
//         <input type="text" ref={inpRef}/>
//     </div>
// }
export default RefCom

Fifth, the latest Hooks basic application

  1. Hook concept
  • The new hook function in the react16.8
  • Providing more logical operations for the functional components dieting
  • You can use state in the case of the preparation of class
  1. Why
  • Resolve the difficulties before taking the state logic components
  • Reduce the cost of learning react in the use of class
  • Can be combined perfectly with clas components
  • Embrace become functional
  • Solve the problem of difficult to understand the life cycle
  1. useState
  • Any type of support incoming data as an initial value
  • It returns an array having two parameters
    • The first parameter data for the monitor data values, corresponding to the defined state
    • The second parameter is a function of changing data corresponding to the setState, but does not merge state
  • Inert support job, execution useState parameters when using (change is not executed)
  • It can be used several times in a functional component
  1. useEffect
  • Side effects hook function
  • Instead componentDidMount, componentDidUpdate and componentWillUnmount lifecycle methods
  • Access to props and state
  • To clear the side effects by returning a function
  • The second parameter may specify dependencies, dependency can be specified by a plurality of array, if the equivalent of an empty array componentDidMount
import React , {useState , useEffect} from 'react'

function BaseHook(){
    const [data , putData] = useState(0)
    const [num , putNum] = useState(() => {
        return 77
    })
    //第二个参数为空数组相当于componentDidMount函数
    useEffect(()=>{
        console.log(data);
        console.log(num);
        let timer = setInterval(() => {
            console.log('111');
        }, 1000);
        //这里的return相当于componentWillUnmount
        return () => {
            clearInterval(timer)
        }
    },[])
    // 相当于componentDidUpdate
    useEffect(() => {
        console.log('=====num 改变了',num);
    } , [num])
    return <div>
        <p>hooks的基础应用</p>
        <p>{num}</p>
        <p onClick={() => {putNum(Math.random())}}>点击改变num</p>

    </div>
}

Sixth, the latest Hokks advanced applications

  1. Custom Hooks
    understood: that is encapsulated into a common logical function to extract class to obtain the desired content by passing in a callback
    Demo: obtaining a current timestamp of the package common logical
//代码查看文件
//base-project/src/components/highHook/custom.jsx
//base-project/src/components/highHook/time.jsx
  1. useContext
  • Define the context of the current component
  • Receiving latest value of the current component of the upper assembly <MyContext.Provider> of
  • Updates will follow the current component data and update the upper component
//代码查看文件
//base-project/src/components/highHook/useContext.jsx
  1. useReducer
  • Overview
    • useState instead of program
    • Shaped to accept such a (state, action) => newState the reducer
    • A return state data and dispatch methods
    • The first parameter is a pure function reducer, the second parameter is the initial value, the third parameter is the initialization function
    • Skip dispathc (internal Objeect.is comparison)
  • scenes to be used
    • More logical operations
    • The new state dependent on the old state
    • Communication between multiple components
//代码查看文件
//base-project/src/components/highHook/useReducer.jsx
  1. useCallback and useMemo
  • useCallback
    • UseEffect with a similar function, detection of certain value changes when the execution Back function
    • The second parameter is dependent on the value, the array is empty, deputies do not rely on any post, once the star of wisdom
    • Do not operate this function side effects
    • This function is suitable for rendering certain calculations or
  • useMemo
    • With the intention of using the same useCallback
    • useCallback (fn, deps) corresponds useMemo (() => fn, deps)
//代码查看文件
//base-project/src/components/highHook/useCallback.jsx
  1. useRef
  • useRef target returns a variable ref
  • ref returned object remains constant throughout the life cycle of components
  • ref .current Object property to a respective node Dom
  • When the ref object content changes, useRef does not notify you
  • Change .current property will not lead to re-render the component
//代码查看文件
//base-project/src/components/highHook/useRef.jsx
  1. useLayoutEffect
  • And similar useEffect
  • the difference:
    • useEffect after the render, it will execute the callback function, and does not block the browser rendering (asynchronous operation .ps: class components componentDidMount and componentDidUpdate are synchronized)
    • Completed before useLayoutEffect it is when you need to do inside the callback dom operation, he will execute the callback function immediately, but will be drawn in any browser
Published 12 original articles · won praise 2 · Views 143

Guess you like

Origin blog.csdn.net/www_lin/article/details/104650654