Introduction and application of redux in react

Posted by taiger on Tue, 21 Dec 2021 18:59:46 +0100

1 what is Redux

1. redux is a js library dedicated to state management (not a react plug-in library).
2. It can be used in react, angular, vue and other projects, but it is basically used in conjunction with react.
3. Function: centrally manage the shared state of multiple components in react application.
4. redux is only responsible for managing the state. As for the change of state driving the display of the page, we have to write it ourselves

2. Under what circumstances do you need to use redux

1. The status of a component needs to be available (shared) by other components at any time.
2. One component needs to change the state (Communication) of another component.
3. General principle: don't use it if you can. If you don't have to work hard, consider using it.

Method of 3redux

subscribe: monitor the status changes in redux. If the status of Redux changes, execute it once

Syntax: store.subscribe( ()=>{} )

dispatch: pass action

Syntax:{type:'',data:''}

getState: get the value of store

4. Redux api

createStore: specifically used to create the most core store object in redux
Applymeddleware: middleware, which is used to support asynchrony with Redux thunk (plug-in, need to be introduced)
combineReducers: used when there are multiple states. You can combine the states into one object

4.1 react Redux api

Provider: you don't need to pass a store to the container component, just wrap a store to the root component

Syntax:<Provider store={store}>

connect: generate a container component and expose it (used by class components)

grammarâ‘ : connect(mapStateToProps,mapDispatchToProps)(UI assembly)
  		You can get it directly from the parameters of the function dispatch
  		mapStateToProps(state)
  	    mapStateToProps(dispatch,ownProps) 

useSelector: equivalent to mapStateToProps of class components

Syntax: const state = useSelector(state=>state)

useDispatch: equivalent to mapDispatchToProps of class components

Syntax:
cosnt dispatch = useDispatch()
dispatch( action Action object )

[note]: using useDispatch()(action object) directly will report an error

5. Redux & react Redux project structure

store
	index.js Create a store container
views
	Lists->This name is to see the file. It's just semantic
		 redux 
			- Actions.js   Returns one or more action objects, generally`{type:'',data:''}`
			- ActionsTypes.js   Returns one or more constants used as Actions and Reducer of type value
			- Reducer.js    Returns a pure function that handles the action object
		 index.js    take actions and reducer Function set export(Convenient management)
		 index.jsx    Container components and UI Combination of components

6. A simple todolist list

src/store/index.js
This file is mainly to create a warehouse
Import the required reducer files

import { createStore, combineReducers } from 'redux';

import { reducer as lists } from '../views/Lists/_index.js'

const reducer = combineReducers({
  lists
})

export default createStore(reducer);

src/router.js
This file is mainly used as a root component
Pass the store down through the provider

import React from 'react';
import App from './App';
import { Provider } from 'react-redux';
import Store from './store'

const Router = () => {

  return (
    <div>
      <Provider store={Store}>
        <App />
      </Provider>

    </div>
  )
}
export default Router

src/List/redux/actions.js
This file mainly returns an action object
The action object must have a type attribute

import * as actiontypes from './actionTypes';
export const addList = (data) => ({ type: actiontypes.ADDList, data })
export const delList = (data) => ({ type: actiontypes.DELLIST, data })

src/List/redux/actionTypes.js
This file mainly returns a constant to prevent letter errors (uppercase by default)

export const ADDList = "ADDLIST";
export const DELLIST = "DELLIST";

src/List/redux/reducer.js
This file returns a pure function, which is used to receive the action from the dispatch, process it and return to the store
Two parameters (preState, action) are injected by default
The initial value of preState needs to be set
When the reducer is called for the first time, it is automatically triggered by the store, and the passed preState is undefined
You must have a default return value

import * as actionTypes from './actionTypes';
const reducer = (preState = [], action) => {
  const { type, data } = action;

  switch (type) {
    case actionTypes.ADDList:
      const result = [
        data,
        ...preState
      ]
      console.log(result)
      return result
    case actionTypes.DELLIST:
      preState.splice(data, 1)
      return [...preState]
    default:
      return preState
  }
}
export default reducer

src/List/_index.js
Summarize action and reducer to facilitate management
There is only one action file
There may be more than one reducer file

import * as actions from './redux/actions';
import reducer from './redux/reducer';

export { actions, reducer }

src/List/_index.js (class component writing method)
Class components get the values and functions of the function mapping in cannect through props

import React,{Component} from 'react';
import { connect } from 'react-redux';
import * as actions from './redux/actions';

class View extends Component{
  

  // Rendering function
  rLsits = () => {
    let { lists } = this.props;
    return lists.map((value, index) => (
      <li key={index}>{value} <button onClick={()=>{this.delfn(index)}}>delete</button></li>
    ))
  }
    // Add data
  send = () => {
    let val = this.inp.value;
    this.props.addLists(val)
    this.inp.value=""
  }
   // Delete data
   delfn = (index) => {
     this.props.delLists(index)
  }
  render() {
    return (
      <div>
        <h2>This is a class Class component operates on array data</h2>
        <input ref={value=>this.inp=value} type="text" />
        <button onClick={()=>{this.send()}}>send out</button>
        {this.rLsits()}
      </div>
    )
  }
}
// mapDispatchToProps is an object
export default connect(
  state => ({ lists: state.lists }),
  {
    addLists: actions.addList,
    delLists: actions.delList
  }
)(View)
// Method 2 mapDispatchToProps is a function
// export default connect(
//   state => ({ lists: state.lists }),
//   (dispatch, ownProps) => ({
//     addLists: data => { dispatch(actions.addList(data)) },
//     delLists: data => { dispatch(actions.delList(data)) }
//   })
// )(View)


// Writing method 3 mapDispatchToProps is null
// You need to pass this. In the UI component props. Dispath passes the action object
// export default connect(
//   state => ({ lists: state.lists }),
//   null
// )(View)

src/List/_index.js (function component writing method)
The value of the function component is obtained through useSelector
The dispatch of the function component is obtained through useDispatch

import React,{useRef} from 'react';
import { useSelector, useDispatch } from 'react-redux';
import * as actions from './redux/actions'
const View = () => {
  let inp = useRef();
  const state = useSelector(state=>state)
  const dispath = useDispatch()
  
  const rLsits = () => {
    console.log('I did')
    return state.lists.map((value, index) => (
      <li key={index}>{value} <button onClick={()=>{delLists(index)}}>delete</button></li>
    ))
  }
  // Add data
  const send = () => {
    let val = inp.current.value;
    dispath(actions.addList(val))
    inp.current.value=""
  }
  // Delete data
  const delLists = (index) => {
     dispath(actions.delList(index))
  }
  return (
    <div>
      <h2>This is an example of a function component operating on array data</h2>
      <input ref={inp} type="text" />
      <button onClick={send}>send out</button>
      {rLsits()}
    </div>
  )
  
}

export default View;

Original link: https://blog.csdn.net/m0_57479235/article/details/119299162

Topics: React