redux members, store members, data flow of redux, and how does redux work with react redux? What are the common API s of react redux, the differences between react redux, redux and vuex?

preface

  1. Redux is a predictable (according to a fixed input, a fixed result will be obtained) state container for javascript applications. It can run on the server, client and native applications. It evolved from Flux. It is simple and easy to use

  2. Centralized management of the status of multiple components in react

  3. redux is a js library dedicated to state management, not a plug-in library for react. It can also be used in other js frameworks, such as vue, but it is basically used in react

  4. You can query the status, change the status and propagate the status in the same place for medium and large projects. The following scenario: the component state needs to be shared and can be obtained anywhere. The component needs to change the global state, and one component needs to change the state of another component. Create a store instance, and other components import and share the store instance

1, redux

1. Three principles of Redux

1) . single data source
2) , State are read-only
3) Use pure functions to perform modifications

2. Installation of Redux

Install stable version:
npm install --save redux
yarn add redux

Add on package: in most cases, you also need to use React binding library and developer tools.
npm install --save react-redux
npm install --save-dev redux-devtools

3.redux members

4.store members

5. Data flow

6.redux operation process

//Installation:
yarn add redux

//1, Create reducer
// Parameters:
// State: original state
// Action: what to do, type of action
// Return value: must be a new state (modified state). The getState() function will call reducer
// The reducer is required to be a pure function (the parameter (input) of the function cannot be modified inside the function, and there must be a return value)
//Modify the state (data) in the store through the component. After modifying the state (data) in the store, you need to respond the data to the component, so you need to use subscribe.
//Its function is to pass in the old state, operate on the state according to the action, and return the new state.
import {createStore} from 'redux'

const reducer = (state,action)=>{
  let {type,payload}=action    
  swtich (type){
  	case XXXXX :{
    	  //Logical processing of data
      	return {
	          ...state,
	          Property name: new value
	      }
  	}   
  	default:
	    return state
  }
}

//2, Create state object
// Data in the warehouse
export default {
    count:0
}

//3, Create a store object (warehouse)
//Use createstore (operation on warehouse and data of warehouse)
//When creating a warehouse, you need to clarify the data stored in the warehouse (state) and the operation on the data (reducer)
store = createStore(reducer,state)
export default store;

//4, Use the warehouse inside the component (such as obtaining warehouse data, modifying warehouse data, adding and deleting)
import store from '...'
store.getState() //Get status, execute once
store.dispatch({type:xxx,payload:ooo}) //Sending action to reducer type is a required parameter
store.subscribe(Callback)  //Triggered when a subscription state updates a state

7. Asynchronous processing in action

The middleware Redux thunk needs to be installed. Redux thunk can enhance the function of dispatch so that dispatch can accept a function as a parameter.

./src/plugins/redux.js

//Installing middleware and refitting redux
import {createStore,applyMiddleware} from 'redux'
import thunk from 'redux-thunk'

let store = createStore(reducer,state,applyMiddleware(thunk));

./src/store/actionCreators.js

//Processing asynchrony
export let ADD =()=>((dispatch)=>{
    axios({
        url:"http://localhost:3000/inc",
    })
    .then(res=>{
        dispatch({
            type:"INCREMENT",
            payload:res.data.num
        })
    })
})


App assembly
./src/App.js

import { increment,decrement,ADD } from "./store/actionCreators";

store.dispatch(ADD());

8.combineReducers extract reducer

When the application logic becomes more and more complex, we need to consider splitting the huge reducer function into independent units, which is called "divide and conquer" in the algorithm. The split reducer is actually used to process a data in the State stored in the Store in reduce. A reducer corresponds to an attribute in the State object tree.
Split a large reducer into several small ones. Note: separate the large states and put them in each reducer. In other words, each reducer writes the data it wants to operate. In this way, a reducer includes data (state) and data operation (reducer).

// ./src/plugins/myRedux.js

import {createStore,applyMiddleware,combineReducers} from 'redux'
import thunk from 'redux-thunk'
import count from "../store/reducers/count";
import todos from "../store/reducers/todos";

let rootReducer = combineReducers({
    todos:todos,
    count:count
});
//The second parameter state is removed (because state is split into each reducer)
export default createStore(rootReducer,applyMiddleware(thunk));


// ./src/store/reducers/count.js

// This is the data to be operated by the current reducer
let initCount = 8;

const count = (count=initCount,action)=>{    
    switch(action.type){
        case "INCREMENT":{
            return count+action.payload;
        }
        case "DECREMENT":{
            return count-action.payload;
        }
        default: return count;
    }
}

export default count;


// ./src/store/reducers/todos
let initState=[] //The data currently operated by the reducer is placed in its own module.

const todos = (todos, action) => {
  switch (action.type) {
    case "ADD_TODO": {
      return [
        ...todos,
        {
          id: action.id,
          text: action.text,
          completed: false
        }
      ]
    }

    case "REMOVE_TODO": {
      const { id } = action;
      todos.map((item,index) => item.id ===id && todos.splice(index, 1));
      return [...todos]
    }

    case "CHECK_TODO": {
      const { id } = action;
      todos.map((item,index) => item.id ===id && (todos[index].completed=!todos[index].completed));
      return [...todos]
    }

    default:
      return todos;
  }
};

export default todos;

//Delete the state file.

//In the assembly:
The writing method is basically unchanged
store.getState().todos

state data is not written in the internal subscription of the class, but can be written in the main entry file to subscribe to the update of store data

2, React Redux

1. Problems in Redux:

1) A large number of store objects appear in the component

2) In redux, all components that use data in state must add store Subscribe() function, otherwise, the data is not responsive

2. What did react Redux do?

Based on the idea of redux, it is specially designed to use redux for react. React redux is a bridge connecting redux and react components

3. Installation

npm install --save react-redux

4. React Redux API

1) Component: the component can get the state
That is, you do not need to use the traditional subscribe () to listen to the state redrawing component

import {Provider} from "react-redux";
import store from './redux/store'

ReactDOM.render((
    <Provider store={store}>
        <App/>
    </Provider>
), document.getElementById('root'));

2) , connect(): link, (return value) is a high-level component used to link the react component and redux
connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])
Function: Connect store and react components together. The mapStateToProps method is called whenever the store changes. The Connect method is a high-level component.

Parameter 1: mapStateToProps function
Function: merge the state in the warehouse into props. Pass in all States to the mapStateToProps function, which returns the specified state data (the state to be merged into the component props). The returned state is merged with the component props.
Therefore, when the store changes, the mapStateToProps method will update the props in the component, and the component will be updated (because the props have changed).

Parameter: state: all States
Return value: the specified state (the state required in the component).

Example code:
const mapStateToProps = (state)=>{
      return {
           count:state.count
      }
}

Parameter 2: mapDispatchToProps function

Function:

Connect dispatch with props. Pass in dispatch and return the bound action method.
Action must be triggered when changing data. Therefore, mapDispatchToProps binds action as the props of the component (the embodiment of contact). The function name to be distributed can be multiple functions. mapDispatchToProps is used to establish the mapping relationship between the component and store.dispatch (action).

Parameters:

dispatch: dispatch
* * ownProps: * * props of the current component, that is, the props passed in when using the tag

Return value:
Object: an object representing all dispatch es

 **Example code:**

import React from "react";
import './App.css';
import {ADD,REDUCE} from "./store/action";
import {connect} from "react-redux";

class App extends React.Component {

  add(){
    this.props.add();
  }

  reduce(){
    this.props.reduce();
  }

  render = () => {
      return (
          <div className="App">
            <p>{this.props.count}</p>
            <input type="button" value=" plus " onClick={()=>this.add()} />
            <input type="button" value=" reduce " onClick={()=>this.reduce()} />            
          </div>
        )
    }
}

export default connect((state)=>{
  return {
    count:state.count
  }
},dispatch=> ({
  add: () => dispatch(ADD()),
  reduce: () => dispatch(REDUCE())  
}))(App);

5. Implementation of react Redux

Installation: npm install --save react-redux

//1. Main entry file index js
import {Provider} from 'react-redux'
import store from './plugins/redux'

<Provider store={store}>
  <App/>
</Provider>
  
 //2. Container component: App component
 
import {connect} from "react-redux";
 
class App extends React.Component {
  add(){
    //dispatch can be called directly with props instead of store
    this.props.dispatch({
      type:"INCREMENT",
      payload:2
    });
  }
    
  render = () => (
   	 <div className="App">
        <p>{this.props.count}</p>  //  Using props, you can directly get the data in the state without the store
        <input type="button" value=" plus " onClick={()=>this.add()} />
     </div>
   )    
}

 //When the container component is open to the public, (turn the state in redux to props) 
export default connect((state)=>{
  return {
    count :state.count    
  }
})(App);

3, The difference between react redux, redux and vuex

Keywords: Javascript Front-end React

Added by ricardo.leite on Tue, 28 Dec 2021 23:22:35 +0200