redux

lrsoy_ 2021-05-04 18:53:40
redux


redux

Why Redux

Communication between components , The data flow is one-way , From the top component through props Passing data down , Lower level components can't pass data up , If necessary, the lower level components need to modify the passed data , You need to pass a method through the top-level component , Use it in lower level components , As projects get bigger and bigger , The operation of transferring data between components , It's going to be difficult , The code doesn't look logical enough .

redux stay react As a data management module in

Redux What is it?

Use scenarios

  • The same state Need more than one Component Share
  • The state of a component , Need to share
  • A certain state needs to be available anywhere
  • One component needs to change the state of another component
  • A component needs to change the global state

install

npm install redux
 Copy code 
npm install react-redux
 Copy code 

store Use

PS:store It's independent , Written in the entry file (index.js)

establish store

  1. Redux Provide createStore This function , Used to generate Store
  2. createStore Function takes another function as an argument , Returns the newly generated Store object
// stay redux Inside the key method to take out , Used to create store
inport { createStore } from 'redux'
// Method name customization 
function fn() {
// Specific operation 
}
const store = createStore(fu)
 Copy code 

obtain store data

  • To transfer data
  1. stay react-redux Export method , Use it to wrap components , In a form similar to attribute parameter passing, we will store Pass on the past
// Using the export method , Package the components , Use 
import { Provider } from 'react-redux'
<Provider store={ store }> <App> </Provider>
 Copy code 

Snipaste_2021-04-27_10-47-21.png

  • Receiving within a component
  1. Need to use again react-redux The tools inside
  2. Call the method , You can pass a parameter when calling , A data can be returned inside a parameter , You can also get data , At the end of the day, the data will be props In the form of , Syntax requires that at the end of the current function call , You also need to return a function , This function needs to be called , Receive a parameter , This parameter is passed to the component that needs to receive data , Which component receives the passed data
  3. connect Function receives a parameter , The general name is state, The internal storage of this parameter is the passed data
import { connect } from 'react-redux'
// props What's in it is ,store Data passed in 
function Head(props) {
return (
<div>{props.count}</div>
)
}
const mod = (state) => ({
// You need to store internal values , Because there is a lot of data stored in the value , Just take those related to components 
count: state.count
})
// Here you need to export this utility function 
export default connect(mod)(Head)
 Copy code 

modify store data ( action )

adopt Action Instructions , It's an object in itself , There's a type attribute , Its value is a string , It's like a custom event is currently defined , At this point, this command is passed to store, Pass on to reducers, Making some logical judgments , And return the value to store.

  • The component to modify data is triggered internally by events or other means

Inside the event, through store The data that's passed through is internal dispatch Method , The internal is action, It's an object , Object use type attribute , Pass a name similar to a custom event , stay reduce It's receiving what's coming type value , Process the data

  • Components that modify data
import React from 'react'
import { connect } from 'react-redux'
function Counter ( props ) {
return (
<>
<button onClick={ () => {
props.dispatch({ type: 'install' })
} }>+</button>
<p>{ props.count }</p>
<button onClick={ () => {
props.dispatch({ type: 'xxxxxxx' })
} }>-</button>
</>
)
}
const instaiu = (state)=>({
count: state.count
})
export default connect(instaiu)(Counter)
 Copy code 
  • reduce Internal reception and processing
/* eslint-disable import/no-anonymous-default-export */
const instalssss = {
count: 10
}
export default (state = instalssss,action ) => {
// You need to use switch sentence , Because there could be a lot of branches 
switch (action.type) {
case 'install':
return {
count: state.count + 1
}
case 'xxxxxxx':
return {
count: state.count - 1
}
default:
return state
}
}
 Copy code 

extract action For the function

to connect Pass in the second parameter

function Counter ( props ) {
return (
<>
// No need to pass parameters
<button onClick={props.increment}>+</button>
// Need to pass parameters
<button onClick={()=> {props.increment_n(5)}}>+</button>
</>
)
}
const mapDispatchToProps = dispatch => ({
// Method , You don't need a second parameter 
increment:function () {
dispatch({
type: 'increment'
})
},
// Method 2 , You need to pass a second parameter 
increment_n(payload) {
dispatch({
type: 'increment_n',
payload
})
}
})
export default connect(instaiu,mapDispatchToProps)(Counter)
 Copy code 

PS: Here are some of these methods , Will be passed on to props, Can pass props Call to use

Automatic generation action Trigger function

By using redux Internal methods , Set automatic generation action Trigger function

  • Introduce methods
import { bindActionCreators } from "redux"
 Copy code 

PS: The method is to receive two parameters internally , Parameter one is an object , The second parameter is dispatch

bindActionCreators({ },dispatch)
 Copy code 
  • What will be configured action Information , In a separate file , Each component has its own file , The way to manage yourself , After exporting the method , Give components in use

Snipaste_2021-04-26_19-35-39.png

const increment = function () {
return { type: 'increment' }
}
const increment_n = function () {
return { type: 'increment_n' }
}
export { increment,increment_n }
 Copy code 
  • Internal use of components

Snipaste_2021-04-26_19-35-27.png

At the time of export , It can be exported uniformly , Receiving in alias

// Alias export 
import * as alink from '../Store/Actions/Counter.actions'
// Receive the exported method 
import { increment,increment_n } from '../Store/Actions/Counter.actions'
 Copy code 

Reference below

const mapDispatchToProps = dispatch => (
bindActionCreators({increment, increment_n },dispatch)
)
export default connect(mapStateToProps,mapDispatchToProps)(Counter)
 Copy code 

Set up action Type constant

take type And define it as a constant , The reason is because of this type The value of is used in multiple places , Also, avoid writing later , There is no grammatical hint , It's easy to make mistakes , So will type The value of type is constant

export const INCREMENT ='increment'
export const INCREMENT_N ='increment_n'
 Copy code 
  • Which page uses , Just import it and use it
import { INCREMENT,INCREMENT_N } from '../Action_types/Counter.action.types'
const increment = function () {
return { type: INCREMENT }
}
const increment_n = function () {
return { type: INCREMENT_N }
}
export { increment,increment_n }
 Copy code 

Reducer Merge and split

PS:reducer What's going on inside , from store Get data inside , And then according to the corresponding instructions , Yes store Internal data changes , Then the processed data will be rendered again

Snipaste_2021-04-26_19-55-19.png

  • Why split

Because in an application , There will be many components , Each component has its own data , It can't all be in one reducer Inside , If you do data management , It's messy in the same file , So each component has to create its own reducer

  • Why merge

Multiple reducer To merge and use ,redux Internally provided methods for merging

// stay reducer Inside the folder , Wear one index.js file , Used to merge multiple reducer file 
import { combinerReducers } from 'redux'
// Put each one reducer Introduce 
// Call methods to merge data 
export default combinerReducer({
// The parameter receives an object , For ease of use , Each key in it is related to its own component reducer The same name , Convenient for later management 
key : Imported reducer //( Key and imported The same name )
})
 Copy code 

example

import { combinerReducers } from 'redux'
import counterReducer from ' route '
import personReducer from ' route '
export default combinerReducer({
counter : counterReducer,
person: personReducer
})
 Copy code 

Merge and convert to the following format

{ counter: {count},person:[{}] }
 Copy code 

After importing the content into , Through store Pass parameters

summary

Folder structure

Snipaste_2021-04-27_10-09-26.png

  • Action_types Folder

This folder stores variables , Inside, there is type Configuration variables , The purpose is to use it in many places , It's also for writing later type Attribute , Causes name inconsistency , Program does not work properly

  • Actions Folder

It's for storing dispatch Configuration options folder , Each component has its own configuration options

  • Raducer Folder

It's a way to store and change data , Inside, it's mainly about data processing , And data storage , Each component corresponds to a .

Reducer How to get data after merging

export default combinerReducer({
counter : counterReducer,
person: personReducer
})
 Copy code 

Snipaste_2021-04-27_10-17-43.png

After data merging , Print the merged results , According to the set key name , Find the corresponding data to use

How to get and modify data inside a component

  • How to get data inside a component

First, through connect Method , He'll receive two callback functions , The first is from store Take out the data , The second is to let react Automatic generation actions Execute function , By using bindActionCreators Generate the execution function , Functions are used to modify data operations .

Snipaste_2021-04-27_10-27-26.png

Parameter transfer and receiving

  • First step , By configuring dispatch, The second parameter can be configured inside , That is, the data options that need to be passed

Snipaste_2021-04-27_10-30-14.png

  • The second step , Components pass parameters

Snipaste_2021-04-27_10-32-09.png

  • The third step , In the process of processing data Reducer It receives parameters , And deal with

Snipaste_2021-04-27_10-36-41.png

redux middleware

Why middleware

For example, in the process of project development , Data is not acquired synchronously , Or there are some asynchronous operations that need to be done before processing data , At this time , adopt action Send events to the middleware , Let middleware handle it , And then back to store, To use .

  • When it's triggered

It's component sending action When the command , Middleware functions will trigger

Register middleware

  • Introduce package name
import { createStore,applyMiddleware } from 'redux'
function reducer( state,action ) {
return state
}
// Define a middleware function 
function middle() {
// In the internal , Specifies that you need to return a function 
return function () {
// Asynchronous processing functions , You need to return a function 
return function () {
// Here is the , When action When triggered , Trigger , Here is to complete the asynchronous operation 
}
}
}
const store = createStore(reducer,applyMiddleware( A function name (middle) ))
 Copy code 

applyMiddleware, Inside is a function name , Which function do you want to be middleware , Write the function name in the position of the parameter

Middleware function parameters

// 3. Receive two parameters getState And dispatch
function middle({ getState, dispatch }) { ??? The effect is not clear 20
// 2. Parameter function , Is to receive the following return actio3n
return function (next) {
// 1. The parameter receives action Instructions sent 
return function ( action ) {
// Simulate asynchrony 
setTimeout(() => {
// If you need to manipulate some data , And then pass it back , Then you can give it to action
action.payload = 100
// Here, after the operation is completed , Or do I have to action hand store
return next(action)
},1000)
}
30
.}
}
 Copy code 

redux-saga Asynchronous resolution scheme

Click the button on the page , Dynamic access to server data

  • First step : Installation package

    • npm install redux-saga
       Copy code 
  • The second step : Import... In the entry file saga, And perform the relevant operations

    • import { createStore,applyMiddleware } from 'redux'
      import createSagaMiddleware from 'redux-saga'
       Copy code 
    • In the use of saga When , Instead of directly turning this function into middleware , It is Call the function first , The returned value is treated as middleware

    • const sagaMiddleware = createSagaMiddleware()
      const store = createStore(toList,applyMiddleware(sagaMiddleware))
       Copy code 
  • The third step : Create a separate folder for Saga To configure , Because every component has its own saga file

    • Pay attention to is , If the saga file , that action There is no need to pass parameters inside the file , It's directly in the saga Inside the file, the requested parameters are passed directly

    • import axios from 'axios'
      // ( One )
      import { takeEvery, put } from 'redux-saga/effects'
      // ( 3、 ... and )
      function* loadPerson () {
      // Processing requests , Then return the requested data 
      // - get data 
      let persons = yield axios.get('http://localhost:3005/api/getUsers').then(res => res.data)
      // Resend a dispatch
      yield put({type: 'load_oerson_success',payLoad:persons})
      }
      // ( Two )
      export default function* personSage () {
      // Parameter one is which method to receive , Parameter two , It's a function , Processing requests to be processed, etc 
      yield takeEvery('load_person',loadPerson)
      }
       Copy code 
        1. First, export the method in the method , Method one is to intercept operations , Method 2 is used to return a new instruction , It's equivalent to triggering a dispatch operation
        2. Export a method , Method to intercept instructions inside , Then the second parameter is used to process the request , And pass the result of the request
        3. Request data operation , And then return the data back
  • Step four : Will be multiple saga File merge

    • import { all } from 'redux-saga/effects'
      import personSage from './person.saga'
      export default function* rootSaga () {
      yield all([
      personSage() // Multiple files can be written directly with commas 
      ])
      }
       Copy code 
  • Step five : stay reducer The internal part of the file receives the instruction to be retransmitted , Processing results

    • function reducer (state = innerText,action) {
      switch(action.type){
      case 'load_oerson_success':
      return {
      person: action.payLoad
      }
      default:
      return state
      }
      }
       Copy code 
      • stay reducer Inside the document case It's not the previous instruction , It is saga In the document put Instructions sent
  • Step six : At the end of the entry file index Inside to receive , Will merge saga File for export , And then through run Method ,run What the method receives is saga File export method ,

    • // It needs to be written in store After creating 
      // Export the merged saga file 
      import rootSaga from './Store/Saga/person.saga'
      sagaMiddleware.run(rootSaga)
       Copy code 

simplify action And reducer

Installation kit

npm i redux-actions
 Copy code 
  • simplify actions

    • import { createAction } from 'redux-actions'
      // expore const increment = () => ({ type: 'increment' })
      // Calling method , Transfer the current type Type passes through 
      expore const increment_action = createAction('increment_action')
       Copy code 
  • simplify reducer

    • // If you need the same high name as the current configuration , You can change the method to use the alias 
      import { handleAction } from 'redux-action'
      // Import instructions 
      import { increment_action } from 'action Configuration path '
      // Initialization data 
      const initText = {
      const :10
      }
      const createReducer = handleAction({
      // If you use the imported instructions directly , It will be parsed as a string , So use it directly 【】 For its package 
      [increment_action]:(state,action) => {
      return // Perform the operation 
      }
      }, initText)
      // Then export the result of execution 
      export default createReducer
       Copy code 
    • Parameter one is instruction , The second parameter is the current reducer The initial value of the , Other files can be used normally

版权声明
本文为[lrsoy_]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/05/20210504184939109z.html

  1. Gallop workflow engine design series 01 process element design
  2. VUE移动端音乐APP学习【十六】:播放器歌词显示开发
  3. Vue Mobile Music App learning [16]: player lyrics display development
  4. jquery cookie
  5. jquery cookie
  6. 体面编码之JavaScript
  7. JavaScript for decent coding
  8. React17 系统精讲 结合TS打造旅游电商平台
  9. React17 system combined with TS to build tourism e-commerce platform
  10. 2021-05-04 hot news
  11. HttpSession对象与Cooike的关系 以及 Cookie对象构造函数问题
  12. gRPC-Web:替代REST的gRPC的Javascript库包
  13. The relationship between httpsession object and cooike and the construction of cookie object
  14. Grpc Web: a JavaScript library package to replace rest grpc
  15. Building reactive rest API with Java - kalpa Senanayake
  16. PDF转HTML工具——用springboot包装pdf2htmlEX命令行工具
  17. Pdf to HTML tool -- Wrapping pdf2htmlex command line tool with springboot
  18. PDF转HTML工具——用springboot包装pdf2htmlEX命令行工具
  19. Pdf to HTML tool -- Wrapping pdf2htmlex command line tool with springboot
  20. Vue.js比jQuery更容易学习
  21. Node.js的Reactor模式 与异步编程
  22. Vue. JS is easier to learn than jQuery
  23. Reactor mode of node.js and asynchronous programming
  24. 详解JavaScript中的正则表达式
  25. Explain regular expressions in JavaScript
  26. 详解JavaScript中的正则表达式
  27. Explain regular expressions in JavaScript
  28. JS: closure
  29. Write your own promise in promises / A + specification
  30. Analysis of the core mechanism of webpack from loader, plugin to egg
  31. On the import and export of webpack
  32. Interpretation of lodash source code (2)
  33. Hexo series (5) writing articles
  34. 有人用过JMeter或用HttpUnit写过测试吗????
  35. Has anyone ever used JMeter or written tests in httpUnit????
  36. JavaScript异步编程4——Promise错误处理
  37. Leetcode 1846. Reduce and rearrange the largest element of an array
  38. JavaScript asynchronous programming 4 -- promise error handling
  39. SQLite是一种经典的无服务器Serverless
  40. 通过Spring Boot Webflux实现Reactor Kafka
  41. SQLite is a classic server less
  42. Realization of reactor Kafka through spring boot Webflux
  43. Focus on the basic knowledge of JS
  44. Node.js与Spring Boot比较? - Ryan Gleason
  45. Compare node.js with spring boot- Ryan Gleason
  46. 「HTML+CSS」自定义加载动画【049】
  47. 「HTML+CSS」自定义加载动画【048】
  48. 「HTML+CSS」--自定义加载动画【047】
  49. "HTML + CSS" custom loading animation [049]
  50. "HTML + CSS" custom loading animation [048]
  51. "HTML + CSS" -- custom loading animation [047]
  52. 使用Akka实现Reactive DDD
  53. Prototype与JQuery对比
  54. Using akka to realize reactive DDD
  55. Comparison between prototype and jquery
  56. Please elaborate the diff algorithm of Vue
  57. On the combination of ecarts and Baidu map, in the Intranet environment to develop offline map, to achieve point, line, range value.
  58. 使用Slonik框架基于Node.js和PostgreSQL处理大量数据
  59. Using slonik framework to process large amount of data based on node.js and PostgreSQL
  60. Netflix使用React制作高性能电视用户界面