React + Redux

stay recat Not in use redux Problems encountered in

stay react The data that components communicate in is unidirectional , Top level components can be accessed through props Property to pass data to lower level components , The lower component can't transfer data to the upper component , To implement the lower level component to modify data , The upper level group needs to transfer the method of modifying data to the lower level component , As projects get more and more popular , It's becoming more and more difficult to transfer data between components

stay react Add redux The benefits of

Use redux Management data , because Store Component independent , Make data management independent of components , The problem of data transfer between components is solved

Use redux

download redux

npm install redux react-redux

redux Workflow

  1. Components through dispatch Trigger action
  2. store Accept action And will action Distributed to the reducer
  3. reducer according to action Type changes the state and returns the changed data to store
  4. Component subscribes to store The state of ,store The status updates in are synchronized to the component

Use react+redux Implementation counter

  1. Create project , And install redux
# If not installed react Scaffolds carry out this order to install reate The scaffold 
npm install -g create-react-app
# establish reate project
create-react-app Project name
# Entry project
cd Project name
# install redux
npm install redux reate-redux
  1. introduce redux, And according to the beginning of the implementation of the code in react Implementation of counters in
//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { createStore } from 'redux'; const initialState = {
count: 0
}
function reducer(state = initialState, action) {
switch (action.type) {
case 'increment':
return {
count: state.count + 1
}
case 'decrement':
return {
count: state.count - 1
} default:
return state
}
}
const store = createStore(reducer) const increment = {
type: 'increment'
} const decrement = {
type: 'decrement'
} function Count() {
return <div>
<button onClick={() => store.dispatch(increment)}>+</button>
<span>{store.getState().count}</span>
<button onClick={() => store.dispatch(decrement)}>-</button>
</div>
} store.subscribe( () => {
console.log(store.getState())
ReactDOM.render(
<React.StrictMode>
<Count />
</React.StrictMode>,
document.getElementById('root')
);
}) ReactDOM.render(
<React.StrictMode>
<Count />
</React.StrictMode>,
document.getElementById('root')
);

Obviously, although the above way can realize the function of the counter , But it can't be used in real projects , Because components are usually in separate files , This is obviously not available in other components Store.

Counter case code optimization - Give Way store Global access

In order to solve Store Getting questions requires using react-redux To solve this problem ,react-redux It provides us with Provider Components and connect Method

  • Provide Components

Is a component You can create it store Put it in a global place , So that components can get store, adopt provider Components , take store It's within the reach of global components ,provider Ask us to put it on the outermost component

  • connect

connect Help us subscribe to store The state of , Help us re render components when the state changes

adopt connect The way we can get store The state of hold store The state in is mapped to props in

adopt connect The way to get dispatch Method

connect Is a function This function gets store The state of , This function must return an object , Everything written in this object is mapped to the component props attribute

connect Call and return a function The returned function needs to be passed in to tell connect You need to map to that component props

  1. newly build Component Folder 、 establish Count.js file
import React from 'react'
function Count() {
return <div>
<button onClick={() => store.dispatch(increment)}>+</button>
<span>{store.getState().count}</span>
<button onClick={() => store.dispatch(decrement)}>-</button>
</div>
} export default Count
  1. introduce Provider The components are placed on the outermost layer , And formulate store
ReactDOM.render(
// adopt provider Components take store It's within the reach of global components provider Ask us to put it on the outermost component
<Provider store={store}><Count /></Provider>,
document.getElementById('root')
);
  1. introduce connect Method according to connect Package components using
const mapStateProps = state => ({
count: state.count,
a: '1'
})
// connect Is a function This function gets store The state of , This function must return an object , Everything written in this object is mapped to the component props attribute
// connect Call and return a function The returned function needs to be passed in to tell connect You need to map to that component props
export default connect(mapStateProps)(Count)
  1. reform Count Component handle action Copy to this file
const increment = {
type: 'increment'
} const decrement = {
type: 'decrement'
}
function Count({count,dispatch}) {
return <div>
<button onClick={() => {dispatch(increment)}}>+</button>
<span>{count}</span>
<button onClick={() => {dispatch(decrement)}}>-</button>
</div>
}

Now the project is ready to run, but Count In the component Submit Action That long string of code affects the readability of the view , So the code still needs to be optimized

Counter case code optimization - Make the code in the view more readable

We want to call a function directly in the view, so that the view code is readable , This needs to be used connect Second parameter of , The second argument is a function , The formal parameter of this function is dispatch Method , This function is required to return an object , The content of the returned object will be mapped to the component's props Attribute

  1. Declare a variable as connect Second parameter in , In this variable, the return execution is different action Object of operation
// connect Second parameter of This argument is a function The formal parameter of this function is dispatch Method Request to return an object The properties in this object are mapped to the component's props On 
const mapDispatchToProps = dispatch => ({
increment (){
dispatch({
type: 'increment'
})
},
decrement (){
dispatch({
type: 'decrement'
})
}
}) // connect Is a function This function gets store The state of , This function must return an object , Everything written in this object is mapped to the component props attribute
// connect Call and return a function The returned function needs to be passed in to tell connect You need to map to that component props
export default connect(mapStateProps, mapDispatchToProps)(Count)
  1. Structure in components props Bind events directly in the view
function Count({count,increment,decrement}) {
return <div>
<button onClick={increment}>+</button>
<span>{count}</span>
<button onClick={decrement}>-</button>
</div>
}

Through this optimization, we found that call dispatch Trigger action The code of the method is repeated , So we need to continue to optimize

Optimize calls dispatch Trigger action Simplify the repetitive code of the method

utilize bindActionCreators To simplify the dispatch Trigger action The operation of ,bindActionCreators To help us generate execution action Function of action

bindActionCreators There are two parameters , The first parameter is zero perform action The object of , The second parameter is dispatch Method

  1. Separate action operation , newly build store/actions/counter.actions.js The document carries out action The operation is placed in this file and exported
export const increment = () => ({type: 'increment'})
export const decrement = () => ({type: 'decrement'})
  1. stay Count.js Import about counter in action, use bindActionCreators Method to generate dispatch perform action function
import { bindActionCreators } from 'redux'
import * as counterActions from './../store/actions/counter.actions' const mapDispatchToProps = dispatch => (bindActionCreators(counterActions, dispatch))
// connect Is a function This function gets store The state of , This function must return an object , Everything written in this object is mapped to the component props attribute
// connect Call and return a function The returned function needs to be passed in to tell connect You need to map to that component props
export default connect(mapStateProps, mapDispatchToProps)(Count)

So far as code optimization is concerned, we find that ,redux It's a combination of code and components , So I need to split it into separate , Why pull away redux Well ? Because we want to make our code structure more reasonable

Refactoring counter , hold redux Related code extraction

hold reducer Function is detached into a separate file 、 Create store Pull out into a separate file

  1. Because in reducer and actions We've all written strings in , But the string doesn't prompt, so we define the string as a constant to prevent us from low-level errors like word errors , newly build src/store/const/counter.const.js file
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
  1. newly build src/store/reducers/counter.reducers.js The document put reducer Function to extract from this file
import { INCREMENT, DECREMENT} from './../const/counter.const'
const initialState = {
count: 0
}
// eslint-disable-next-line import/no-anonymous-default-export
export default (state = initialState, action) => {
switch (action.type) {
case INCREMENT:
return {
count: state.count + 1
}
case DECREMENT:
return {
count: state.count - 1
} default:
return state
}
}
  1. change actions The string in is the leading variable
import { INCREMENT, DECREMENT} from './../const/counter.const'
export const increment = () => ({type: INCREMENT})
export const decrement = () => ({type: DECREMENT})
  1. establish src/store/index.js file , Create... In this file store And export
import { createStore } from 'redux';
import reducer from './reducers/counter.reducers' export const store = createStore(reducer)
  1. In the introduction of store In the project store Introduce in the file store
import React from 'react';
import ReactDOM from 'react-dom';
import Count from './components/Count';
import { store } from './store'
import { Provider } from 'react-redux'
/**
* react-redux Give Way react and redux Perfect combination
* Provider Is a component You can create it store Put it in a global place So that components can get store
* connect It's a method
*/ ReactDOM.render(
// adopt provider Components take store It's within the reach of global components provider Ask us to put it on the outermost component
<Provider store={store}><Count /></Provider>,
document.getElementById('root')
);

by action Pass parameters , Expand the counter case

This counter case has realized the operation of click button plus one minus one , Now there is a new demand. We need to add or subtract a value, such as add five minus five

It needs to be right action Passed parameters

  1. In the view, click bind function to pass in parameters
function Count({count,increment,decrement}) {
return <div>
<button onClick={() => increment(5)}>+</button>
<span>{count}</span>
<button onClick={() => decrement(5)}>-</button>
</div>
}
  1. stay dispacth perform action Accept the parameters and pass them to action in
export const increment = payload => ({type: INCREMENT, payload})
export const decrement = payload => ({type: DECREMENT, payload})
  1. stay reducers Receive the parameters and deal with them accordingly
export default (state = initialState, action) => {
switch (action.type) {
case INCREMENT:
return {
count: state.count + action.payload
}
case DECREMENT:
return {
count: state.count - action.payload
} default:
return state
}
}

Original address :https://kspf.xyz/archives/10/

stay react Use in redux And the implementation of counter case more related articles

  1. react series ( 5、 ... and ) stay React Use in Redux

    The last one showed Redux Basic use of , You can see Redux It's very easy to use , Not limited to, React, It can also be in Angular.Vue Etc , As long as you need Redux The design idea of the place , You can use it . This article focuses on Rea ...

  2. stay React Use in Redux

    This is a Webpack+React Chapter 6 of the series configuration process record . Please refer to : Chapter one : Use webpack.babel.react.antdesign Configure the single page application development environment Second articles : Use react-rout ...

  3. react Use in redux Simple case explanation

    Why do I want to use redux? Some time ago, I got started react, Recently in use react In the process, it is found that there is an urgent need for communication between components , Especially in axios When requesting back-end data asynchronously , Such a demand is particularly strong ! for instance : ...

  4. react For in the redux Encapsulation

    const createStore = (reducer)=>{ // default state object let state = {}; // Put all the subscribed events in this array let listeners = ...

  5. stay React Use in Redux Data flow

    problem : What is data flow ? Why use data streams ? answer :1. Data flow is our behavior and corresponding abstraction 2. Using data flow helps us define the corresponding response of the behavior problem : React The relationship with data flow 1.React Is pure V The front end frame of the layer ...

  6. How to be in Africa React Project use Redux

    The author of this article : He has a big beard Link to the original text :https://scriptoj.com/topic/178/ How to be in Africa -react- Project use -redux Reprint please indicate the source , Keep original links and author information . Catalog 1. Preface 2. ...

  7. How to be elegant in React Project use Redux

    Preface Maybe your current project hasn't been applied yet Redux The degree of , But there's no harm in knowing in advance , This article will not be used by Amway Redux Concept First of all, what frameworks and tools will we use ? React UI frame Redux State management tools , And ...

  8. Elegant in React Project use Redux

    Concept First of all, what frameworks and tools will we use ? React UI frame Redux State management tools , And React It doesn't matter , other UI Frameworks can also be used Redux react-redux React plug-in unit , effect : Convenient in ...

  9. react Jump in the middle interface A Interface jump B Interface , return A Interface ,A The state of the interface remains unchanged redux Of state Method

    As I said in the last article react Middle interface A Jump to the B, return A,A The state of the interface remains unchanged , In the first part, we use the traditional localStorage Method , Now use the second one redux Of state Method to achieve this function Now I've just come into contact with red ...

  10. react in redux The understanding of the

    Definition redux It can be seen as flux An advanced version of , It is mainly used for react In the public state ( data ) Management of redux Underlying principle redux There is one createStore Method , This method allows users to create common storage space ,createSto ...

Random recommendation

  1. WebSockets Basics

    Network socket is the next generation WEB Application two way communication technology , It's based on an independent socket And need client browser support HTML5. Once you understand network socket and WEB Server connection , You will be able to send data from the browser to the server and receive ...

  2. Javascript Simple button search function

    Study JavaScript I think the real feeling is that it can be designed at will ,“ Nothing can't be done, only unexpected !” Even if it's simple , But the complexity of everything starts with simplicity . The foundation starts with ! This is a super simple one I made myself " Search engine " Button , ...

  3. mangos build

    github Address :https://github.com/mangos/MaNGOS MaNGOS  yes ( Massive Network Game Object Server) Abbreviation . Due to Blizzard's support for ...

  4. [Qt primary ] solve in QMainWindow and QDockWidget Failed to add layout

    First contact Qt, The tutorial used was written by Lu Wenzhou <Qt5 Development and examples > A Book . It's about QDockWidget.QStackedWidget Introduction and examples of these classes . First of all, the book is very clear , generation ...

  5. [Swift]LeetCode405. Convert numbers to hexadecimal numbers | Convert a Number to Hexadecimal

    Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s compl ...

  6. Linux System ( Four )LVS Cluster load balancing NAT Pattern

    preface mention LVS, Let's start with Dr. Zhang wensong , I don't know how to write this article anyway . Dr. Zhang Da , I created this when I was a blogger lvs Software projects , But he advocates the spirit of open source , In the user's suggestions and feedback , This open source software that took him two weeks to develop is constantly being rebuilt ...

  7. Python Exception handling mechanism 、 debugging 、 test

    Be similar to Java Of try..catch..finally Java For the try_except_finally try: print('try...') r = / print('result:', r) ...

  8. Ubuntu18.04 Next to the Jupyter-NoteBook Set the default working path ( attach Win Set up )

    Last one Jupyter The article :https://www.cnblogs.com/dotnetcrazy/p/9201976.html Linux Generate configuration files :jupyter-notebook --gen ...

  9. python The base type — Numbers (Number)

    Python3 Support  int.float.bool.complex( The plural ). stay Python 3 in , There is only one integer type int, Expressed as a long integer , No, python2 Medium Long. Like most languages , Count ...

  10. 『Python CoolBook』C expanded memory bank _ Its 4 _ Structure operation and Capsule

    Click to enter the project One .Python Generate C Language structure C The structure of language is passed on to Python It's encapsulated in capsules (Capsule), We want a structure like this to operate , You need to Python Pass in x.y Two floating-point numbers , type ...