Introduction of Hooks

Hooks are a new feature in React V16.7.0-alpha. It allows function components to have their own state. React 16.8.0 stable version supports Hooks. This article demonstrates the use of Hooks in a project.

useState

import React, { useState  } from 'react';
function Example() {// declare a new state variable called "count" const [count,setCount] = useState(0);

    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>
                Click me
            </button>
        </div>
    );
}

export default Example;
Copy the code

useEffect


import React, { useEffect  } from 'react';
function Example() {componentDidMount useEffect() => {console.log() {componentDidMount useEffect() => {console.log()'componentDidMount')}, []); // componentDidMount useEffect(() => {console.log())'componentDidMount')
        return ()=>{ //componentWillUnmount
            console.log('componentWillUnmount')}}, []); ComponentDidMount and componentDidUpdate useEffect(() => {console.log())'Similar to componentDidMount and componentDidUpdate:')});return (
        <div></div>
    );
}

export default Example;

Copy the code

ComponentDidMount, componentDidUpdate, componentWillUnmount use method

useMemo

import React, { useMemo  } from 'react';
exportdefault ({a}) => { const exampleA = useMemo(() => <div>{a}</div>, [a]); // render when the value of a changesreturn exampleA
}
Copy the code

useRef

import React, { useRef  } from 'react';

export default ({a}) => {
    const inputEl = useRef(null);
    return <input ref={ inputEl } type="text" />
}
Copy the code

React-router Obtains route parameters

import React from 'react';
import { withRouter } from 'react-router-dom';

export default withRouter((props) => {
    return <div>{props.match.params.id}</div>
})

Copy the code

Use of React-Redux and Redux-saga

import React, { useEffect } from 'react';
import { connect } from 'react-redux';

const mapStateToProps = (state) => {
  return {
      list:state.list
  };
};
const mapDispatchToProps = (dispatch) => {
  return{getList ()=>{},// just instance usage}; }; const useAddField = (props:Props) => { useEffect(()=>{ console.log('---------- first render ')
      this.props.list();
      return ()=>{
        console.log('-- -- -- -- -- -- -- out'}},[]) //componentDidMount console.log(props. List) // Reduxreturn <div></div>
};
export default connect(mapStateToProps, mapDispatchToProps)(useAddField);
Copy the code

Reference documentation

The React website

React Hooks FAQ

Refer to the blog