preface

It’s not enough to learn Redux at a level where you can use it, but to figure out how best to use it.

Redux Best Practices

When we first learn to use Redux, we almost always encounter some problems, and here are the two problems.

  1. We know that when we use global data in a component, there are several steps

(1) Import store file.

(2) Call the state assigned to the component by the store.getState() API.

Let’s think, when we have a lot of components, do we need to do this for each component?

  1. About immutable data.

(1) When reducer deals with different types, we need to make a deep copy of state to change and then return.

So we have a deep copy of what optimization plan, is it necessary to use recursion to write a deep copy function, you can think from the data structure 🤔.

The above two points are actually some questions raised by my mentor for my code.

React-redux

What is React-redux?

React-redux redux redux redux redux redux redux redux redux

Since it is convenient to use Redux, let’s talk about what is convenient and what problem is solved.

Redux will wrap all of our components in the react project and then pass values to the incoming store. React-redux provides a parent component that has its own state, store, and functions that share global data with the props of all components. All of the react components are his sons, and the sons are only responsible for rendering. The parent handles state (store) and passes it to you, so you can just fetch it from props. That solves the first problem.

The above paragraph is my own words. For some technical terms, I have to read Nguyen Yifeng’s article for a clearer explanation of react-Redux

So let’s do some in code.

1. About Provider

This Provider is the parent component we mentioned above

import React from 'react'
import ReactDOM from 'react-dom'
import store from './store'
import { Provider } from 'react-redux'
import './index.css'
import TodoApp from './TodoApp'

// Introduce the Provider in the react-redux and pass it to the global data store.
ReactDOM.render(
    <Provider store={store}>
        <TodoApp />
    </Provider>.document.getElementById('root'))Copy the code
2. About Connent ()

React-redux provides a connect method to link the child component to the Provider component.

import { connect } from 'react-redux'
class TodoApp extends Component {
    constructor(props) {
        super(props);
        this.state = {  }
    }
    render() { 
        return ( 
            <p>TodoApp</p>); }}export default connect()(TodoApp)
Copy the code

If the link is as above, it is not possible. Note that connect also accepts two parameters

1) The first parameter mapStateToProps

The mapStateToProps function returns a mapping object from the external (state) to the internal props. Here we directly map all the data in state

import { connect } from 'react-redux'

const mapStateToProps = (state) = > {
  return state
}

export default connect(mapStateToProps, null)(TodoApp)
Copy the code

This allows us to use global data in the props of our child component.

2) The second parameter mapDispatchToProps

So what is this mapDispatchToProps for? The mapDispatchToProps method is a mapping to the Store. dispatch method, because we can make global data change requests in child components. It can be a function or an object.

If mapDispatchToProps is a function. There are two parameters, dispatch and ownProps (the props object of the container component).

const mapDispatchToProps = (dispatch, ownProps) = > {
    return {
        handleInputValue(){
            dispatch({
                type: 'SET_VALUE'.value: ownProps.value }); }}; }Copy the code

If mapDispatchToProps were an object, the key would be a function that would be treated as an Action Creator, and the returned action would be issued automatically by Redux. The mapDispatchToProps object would look like this.

const mapDispatchToProps = {
    handleInputValue: (e) = > ({
        type: 'SET_VALUE'.value: e.target.value
    })
}
Copy the code

3. Immer

The introduction of immer

Immer (German: always) is a small package based on the ES6 proxy implementation. It makes it easier for you to handle immutable state. It “copies” referential data types in JavaScript at minimal cost, because the deep-copy approach is costly and affects performance.

Put up a picture and feel the charm

In the figure, we can see that it does not recurse and copy, but first finds different nodes to copy, and the same nodes refer to the original data node.

A simple implementation of IMmer will follow. Here’s how to use it.

1. Install through NPM
npm install immer --save
Copy the code
2, use,
/ / introduction
import produce from "immer"

// Here is our raw data
const baseState = [
    {
        todo: "Learn typescript".done: true
    },
    {
        todo: "Try immer".done: false}]// use produce to manipulate our baseState function
const nextState = produce(baseState, draftState= > {
    draftState.push({todo: "Tweet about it"})
    draftState[1].done = true
})
Copy the code

The usage is relatively simple, so we can use IMmer to make data backup in reducer, and abandon the original method of deep copy function.

So we solved the two problems we had above.