Introduction before learning

1. What is React-redux

Redux is a predictable state container for JavaScript applications.

Simple understanding: Similar to VuEX, a kind of storehouse of state, you can go to the storehouse to get what you want.

2. What is the function

To achieve data sharing, it can be used globally.

3. Three core principles

1. Single data stream =====>**state(Objecct)** 1. Globally shared values are all under this object. 2. State features ======>** read-only ** 1. Distribute an action, which is a common object that describes the event that has occurred. 3. Change data source state through pure functionsCopy the code

The flow chart of 4.

! [image-20210330001929308](/Users/renchaoqiong/Library/Application Support/typora-user-images/image-20210330001929308.png)

What is the relationship between view components, Store repositories, Actions, reducer?

The following features can be seen from the figure

1. The store can see * * * * is connected action * * * *, * * * * view, reducer for * * * * in the middle of the link between 2. The view layer can obtain required values from **store** 3. The contents of the **store** repository can be modified by **action** dispatch** 4Copy the code

Installation and reference

1. Install

// If you use npm:
npm install redux react-redux -save

// Or if you use Yarn:
yarn add redux react-redux -save
Copy the code

2. Use

  1. Create the reducer

    Reducer is a js pure function that internally does two things :1. Define the default state data 2. Export a function that handles the values that need to be modified.

    /* ./store/reducer.js */
    // 1. Define the status data of the default data and return the status data
    const defaultState = {
      value: 'Little watermelon'.arr: []}// 2. Export a function
    const reducer = (state=defaultState, action) = > {
      	// Since state cannot be changed directly, a new object needs to be copied
       	let newState = JSON.parse(JSON.stringify(state)); 
        switch (action.type) {
        	case 'change_value':
            newState.value = action.inputValue
            return newState
          case 'add_value':
            newState.arr.push(state.value)
            return newState
          default:
            return newState
        }
    }
    export default reducer; 
    Copy the code
  2. Create the store

    Because the reducer cannot directly obtain the view after modifying the value on the store, it must go through a repository called store.

    /** ./store/index.js */
    
    import { createStore } from 'redux'; 
    import reducer from '.. /reducer/index'
    const store = createStore(reducer)
    export default store;
    
    Copy the code
  3. View gets the value of state in store

    // ./src/inddex.js
    import store from './store' // reference the store repository
    constructor(props) {
      super(props)
      this.state = store.getState(); // Get the value of the repository
        store.subscribe(this.storeChange.bind(this)); // Subscribe to listen
    }
    Copy the code
  4. Send a request to modify the state value

    / / view
    <div style={{ margin: '20px'}} ><Input placeholder="Input field" style={{ width: '200px', marginRight: '10px'}}onChange={(e)= >{this.handlechange (e)}}/>
      <Button type="primary" onClick={()= >{this.handlecreate () // here}}> Add</Button>
      <List
        style={{ marginTop: '20px', width: '275px'}}bordered
        dataSource={this.state.arr}
        renderItem={item= > (
          <List.Item>
            {item}
          </List.Item>)} / >
    </div>
    
    
    /** Send the action through the store.dispatch() method */
    
     // When the input box value changes
      handleChange(e) {
        // Change the value in store
        const action = {
          type: 'change_value'.// type is the name, which is mandatory
          inputValue: e.target.value // This parameter is optional
        }
        store.dispatch(action)
      }
      // Confirm to add
      handleCreate() {
        const action = {
          type: 'add_value'
        }
        store.dispatch(action)
      }
    Copy the code

We can see that the values in the repository have changed, but the view has not been rerendered because the view has not received the message that the repository has changed the value.

  1. To subscribe to

    1. Insert in step [3] above
    import store from './store'
    constructor(props) {
      	super(props)
      	this.state = store.getState(); // Get the value of the repository
        store.subscribe(this.storeChange.bind(this)); // [insert] subscribe to listen below [2]
    }
    render(){....}
    // The view can be rendered when store is changed
    storeChange() {
        this.setState(store.getState())
     }
    Copy the code

Above operations, is every time we need to use the store warehouse value or modification of the state, the need to refer to the warehouse files, then register to monitor subscription, etc., so every time they are conducted by using the component relative repetitive work, so in the react, you can use the provider and connector.

Providers and connectors

1. To provideprovide

The provider provide simply wraps it around the outermost layer of the entry component, and all of its children have access to the store value.

// Import file
import store from './store' // Reference the created store repository
import APP from './APP' 
render() {
    return} <Provider store={store}><App />
      </Provider>
    )
  }
Copy the code

2. The connectorconnect

The connector connects the React component to the Redux Store.

Provide components that wrap the entire application. All react components become child components. Receives the Store of Redux as props, passing it through the context object to connect on the descendant component

Therefore, the React component, after using the connect connector, can use this.props to get data (which is how a child component gets its parent).

Method of use

The connect function has two parameters mapStateToProps mapDispatchToProps

Parameter 1: mapStateToProps receives data

import { Component } from "react";
import { connect } from 'react-redux';

class ComB extends Component {
  render() {
    return(
      <div>{this.props.XXX}</div>)}}// Accept data information
const mapStateToProps = (state) = > {
  return {
    XXX: state.count
  }
}
/** * connect(receive data fn, send data FN)(component) */
export default connect(mapStateToProps, null)(ComB)
Copy the code

Parameter 2:mapDispatchToProps sends modified data

import { connect } from 'react-redux';
class ComA extends Component {... }// Send the data message
const mapDispatchToProps = dispatch= > {
  return {
    sendAction: () = >{
      dispatch({
        type: 'increase'})}}}/** * connect(receive data fn, send data FN)(component) */
export default connect(null, mapDispatchToProps)(ComA)
Copy the code

If react requires the use of React-Redux, providers and connectors are recommended. See React-redux for basic usage