Some personal understanding of React higher order components

1. Stateless Components

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;

}//This type of component does not have its own state

2. web components

Such components generally have their own state, and they can update their state through setState(). We generally use such components to implement some logical functions, and they can use stateless components. Of course, he can also use it for other components, which also reflects the good encapsulation of react components. For example the following components:

class HelloMessage extends React.Component {

constrcutor(props){ super(props)};

componentDidMount(){}

  render() {

    return <div>

 <Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />

              </div>;

  }

}

In this type of component, we can do many things, such as exchanging data with the background. Almost all the small demos written by yourself can use this method to update themselves, get data in the hook function, update the state in the event handler function and send data to the background. E.g:

class HelloMessage extends React.Component {

constrcutor(props){ super(props)};

componentDidMount(){

    let url = '//The background path of the request'

    fetch( url , {//Configuration parameters

        method: "POST",

        header : { "content-type : application/json"} 

    }).then(response=>response.json()).then(json=>{

   //Assume we successfully got the data json

  this.setState({ json })//We can get the data here and set it to its own state, the render method will be called to update the view

 })

}

handleChange = () =>{}//If you need to interact with the background data, continue to send the fetch request here

  render() {

    return <div onClick={this.handleChange}>{this.state.json}</div>;

  }

}

In this way, we have completed a complete process of interaction in the background. We only need to call fecth in the handleChange method. After getting the updated data in the background, drop setState({}) to update the view.

3. Higher order components

On the official documentation, what is a higher-order component and why you need a higher-order component. Higher-order components can be thought of as a means to improve code quality (so you don't have to do repetitive things, why not?). A higher-order component is not a component. It is actually a function. This must be clear, so that you can start writing a higher-order component.

https://reactjs.org/docs/higher-order-components.html
function higherOrderComponent(WrappedComponent , [params]) {
  return class MyComponent extends React.Component {
    componentWillMount() {
      let data = fetch()//The data obtained after the call is given to data
      this.setState({data});
    }
    render () {
      // Continue to pass the properties passed to the current component to the wrapped component via {...this.props} WrappedComponent
      return <WrappedComponent data={this.state.data} {...this.props} / >
    }
  }

}

In the higher-order component above, we call the higherOrderComponent method, and we get an interesting component. This component not only contains all its own properties, but also gets a props.data, which contains the data obtained by fetch. I did not use the second parameter params. In fact, in this example, it can be passed as url Give the parameter of fetch, so that if there are two components that need to fetch data, we only need to call this method. In the component MyComponent, of course, we can do more than just fetch a piece of data! ! ! You can definitely define some event functions!

In order to describe this component more clearly, we adopt a clear definition

function higherOrderComponent = (params) => (WrappedComponent) =>{
  return class extends Component {
    componentWillMount() {
      let data = fetch()//The data obtained after the call is given to data
      this.setState({data});
    }
    render() {
      // Continue to pass the properties passed to the current component to the wrapped component via {...this.props} WrappedComponent
      return <WrappedComponent data={this.state.data} {...this.props} />
    }
  }

}

Yes, is it very familiar, yes. This is what the connect method in redux does

connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])(Component)

Here you can think that the data obtained by fetch is mounted to the WrappedComponent in the connect method, which is what the mapStateToProps method does.

And getting the method from the store to WrappedComponent is what mapDispatchToProps does!!! It's amazing, I think too. . . This thing also reminds me of closures ~ far away. In redux, we get a component connected to the redux store through const MyCompoenet = connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])(Component). If you are new to redux, what are you waiting for, learn it now! This is also to reflect the role of higher-order components. In react-router when you use withRouter, you will find that this is also a higher order component. . (It's so verbose because it's really used a lot!).

4. Encapsulate react components (chat)

function MyComponent(props) {
    function handleChange (value) {
           props.handlechange(value)
    }  
      return (
        <div>
        <Component value={props.value} //绑定值
                    onChange={handleChange}
                    />
        </div>
      )    

  }

export defaule MyComponent;

After we write the Component component, we can use the closure method to expose some interfaces to the Component component. The above MyComponent method exposes the hangChange interface. We are external and can use this interface in this way,

import MyComponent from '/path';

<MyComponent hangleChange={//external method} value = {//external value}/>//Exposing other interface calls, only two interfaces are exposed here, one is used to handle value changes, and the other is vaue that binds props of. I believe that if you are learning packaging, you will be inspired.

I hope to correct me if I write badly. I have also been learning the react family bucket. If you want to learn together, you can contact me. work hard together!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324731618&siteId=291194637