Brief introduction of react and Redux integration technology

Time:2021-1-28

Note: reading this article needs to have a certain understanding of redux. Students who don’t know Redux can read this article firstIntroduction to Redux Technology Architecture (1)

1. Introduce react Redux into react

In order to make Redux work better with react, Facebook has developed a special NPM package — react redux. You can introduce your project in this way:
npm install --save react-redux
Of course, it’s OK not to reference (Redux package must be referenced), but it will increase the amount of development and bring some additional performance overhead.

2. Display components and container components

The basic development idea of react binding library in Redux is to separate display components from container components. The display component is only responsible for page rendering, does not process data, does not maintain state; the container component is responsible for the running logic of the page, obtains the message in the display component, processes internal data, updates state, etc.
Brief introduction of react and Redux integration technology

3. Implementation of display components

After the introduction of Redux into react, there is only a single state tree in the application. Each component of react can discard the state related logic and get it from props instead, including some user event behaviors to be executed.
After the introduction of Redux, the react component becomes:

class MainContent extends React.Component{
    constructor(props){
        super(props);
        this.sortResult = this.sortResult.bind(this);
        this.showSlider = this.showSlider.bind(this);
    }
    sortResult(data){
        this.props.setPhoto(data);
    }
    showSlider(index){
        this.props.showSlider(index);
    }
    componentDidMount () {
        this.props.fetchPosts();
    }
    render(){
        let {isFetching, isValidate} = this.props;
        let sliderNode = null;
        if(this.props.photo.length){
            sliderNode = <PhotoSliderContainer data={this.props.photo} />;
        }
        return (
            <div className="mainContent">   
                <Header  />
                <SortContainer data={this.props.photo} sortResult={this.sortResult}/>
                <PhotoItemsContainer data={this.props.photo} showSlider = {this.showSlider}/>
                {sliderNode}
            </div>
        );
    }
};

As you can see, the maincontent component has almost no logical processing except presentation (the logic of subscribe and dispatch is put into the container component), and all data is processed through the this.props From the parent component.

4. Implementation of container component

Container component can associate presentation component with redux. Technically, the container component is to use store.subscribe () read part of the data from the Redux state tree and provide the data to the component to be rendered through props. It is suggested that each presentation component corresponds to a container component, so that the mapping relationship can be found clearly.

Mapstatetoprops function

As you can see from the name, this function implements the mapping from state (defined in reducer) to the presentation component props. The sample code is as follows:

const mapStateToProps = (state, ownProps) => {
    return {
        photo : state.photomainReducer.photoData,
        video : state.photomainReducer.videoData,
        isFetching : state.photomainReducer.isFetching,
        isValidate : state.photomainReducer.isValidate
    }
}

The passed in state is the only state tree in the application. We read the state from the reducers of the corresponding components and map it to a custom attribute respectively. In this way, we can directly call the corresponding attributes (props) in the display component.
Mapstatetoprops will subscribe to the store. Whenever the state is updated, it will automatically execute and recalculate the parameters of the UI component, thus triggering the re rendering of the UI component.

Mapdispatchtoprops function

We can also guess that this function is used to map the return value of the expected dispatch method to the props of the presentation component. The sample code is as follows:

const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        slider:(data) => dispatch(photomainAction.showSlider(data))
    }
}

For example, we want to dispatch the action of a showslider. After mapping through this method, we can directly write as follows:

this.props.slider(data)

Mapdispatchtoprops encapsulates the dispatch method. In addition, it can be further encapsulated by the bindactioncreators function provided by redux. The above code can be rewritten as follows:

const mapDispatchToProps = (dispatch, ownProps) => {
    return bindActionCreators({
        slider:photomainAction.showSlider
    },dispatch);
}

If the action name in import is the same as the attribute name you want to define, it can even be simplified

const mapDispatchToProps = (dispatch, ownProps) => {
    return bindActionCreators({slider},dispatch);
}

Connect function

The above two methods implement the mapping of state and action to props. We also need to connect the two functions together and associate them with a specific presentation component, so that we can use this mapping relationship in the presentation component. The sample code is as follows:

const PhotomainContainer = connect(
    mapStateToProps,
    mapDispatchToProps
)(Photomain);

Among them, photomain is a display component.
Each container component contains a corresponding display component. We can combine these container components as a common react component. The last step of integration is how to transfer the store into each component.

5. Enter the store

The store stores a single state tree of the whole application. All container components need to be read from the store. We can pass the store as an attribute to each component, and the child components can be obtained through props. However, if the nesting is too deep, it will be very troublesome to write. Fortunately, react Redux provides a component called provider, which allows all components to access the store (his implementation principle is actually to use the context function of react), without having to display layer by layer.

ReactDOM.render(
    <Provider store={store}>
        <PhotomainContainer></PhotomainContainer>
    </Provider>,
    $(".main-wrap")[0]
);

It should be noted that there can only be one component in the provider, so all components need to be encapsulated into one component first, and then wrapped by the provider.

6. Summary

With the introduction of Redux, react completely breaks away from the management of data state, and can focus on the display of view. In fact, this is what react is good at. Looking at react alone, we can’t even feel the existence of Redux, which makes the logic layer and view layer clearer (Redux is responsible for logic, react is responsible for view). Of course, part of the reason is due to the good encapsulation of react Redux package.

The above is a simple implementation of the integration of react and redux.

reference resources

Redux Chinese document
Rudimentary course of Redux – Ruan Yifeng

Recommended Today

Practice of query operation of database table (Experiment 3)

Following the previous two experiments, this experiment is to master the use of select statements for various query operations: single table query, multi table connection and query, nested query, set query, to consolidate the database query operation.Now follow Xiaobian to practice together!Based on the data table (student, course, SC, teacher, TC) created and inserted in […]