This is the sixth day of my participation in the August Text Challenge.More challenges in August

Redux

Redux is a predictable state container.

Liverpoolfc.tv: redux.js.org/

Create a Redux project to debug with Nodejs

Creating an ID card

npm init
Copy the code

Install dependencies

npm install --save redux
Copy the code

To create the app. Js

var redux = require("redux"); // Create a function called reducer. const reducer = (state = {"a" : 10} , action) => { if(action.type == "ADD"){ return { "a" : state.a + 1 } }else if(action.type == "MINUS"){ return { "a" : state.a - 1 } } else if (action.type == "PINGFANG") { return { "a" : state.a * state.a } } return state; } const store = redux.createstore (reducer); // Get a console.log(store.getState(). // issue the ADD command store.dispatch({"type" : "ADD"}); //10+1 store.dispatch({"type" : "ADD"}); //11+1 store.dispatch({"type" : "ADD"}); //12+1 // get a console.log(store.getState(). 13 / / / / a subtraction command store. Dispatch ({" type ":" MINUS "}); A console.log(store.getState().a); // 12 store.dispatch({ "type": "PINGFANG" }); //12*12 // get a console.log(store.getState(). / / 144Copy the code

When the store changes after dispatch is sent and no updates are attempted, the subscribe method is used

Force a refresh in the componentDidMount declaration cycle within the component

componentDidMount(){
    store.subscribe(()=>{
      this.forceUpdate()
    })
}
Copy the code

Add subscribe to the import file and execute render again

import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; import store from './store' ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') ) store.subscribe(()=>{ ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>,  document.getElementById('root') ) })Copy the code

Use redux checkpoints

  1. CreateStore create store
  2. Reducer initialized and modified the state function
  3. GetState Gets the status value
  4. Dispatch submit update
  5. Subscribe to

Predictable state containers

Redux is dedicated to managing state

One of the main advantages of using Redux is that it helps with application shared state. If two components need to access the same state, the phenomenon of two components needing to access the same state at the same time is called “shared state.” You can promote the state to a nearby parent, but if the parent is several components up in the component tree, passing the state down as a property becomes tedious. In addition, components between parent and child components don’t even need to access this state at all!!

Redux not only enables us to store data in an organized manner, but also allows us to quickly access that data anywhere in the application. Just tell Redux which component needs which data, and it takes care of everything for you!

With Redux, you can control when, why, and how your state changes.

Store: Single data source

Steps: Introduce the createStore function, introduce the Reducer governor file, create a store, and try to pop up an A.

Store contains the global state of an application, all stored in one object tree. The state in redux is read-only, and the React component cannot write the React state directly. Instead, it issues an Intent to update the state (only a pure reducer function can change the state).

Store is used to hold state. There is only one store per project and only one reducer in each store (of course it can be split and merged into an index file)

The store has the following responsibilities:
Holds the state of the app
Allow getState() to getState
Allows state to be changed via dispatch
You can only have 1 store in your app.
When you want to slice your data logic, you should consider splitting the Reducer rather than the store.
Creating a Reducer is simple, and using combineReducers() you can easily merge multiple reducers into one. And passed into createStore()

To get the value of Store State, use store.getState()

The complex state

State can be a complex structure that doesn’t look good on the line at this point and can be distilled into variables (constants)

var redux = require("redux"); / / initial state const initState = {students: [{" id ": 1," name ":" xiao Ming ", "age" : 12}, {" id ": 2," name ":" small strong ", "age" : 14}, {" id ": 3," name ":" app ", "age" : 13}]} / / reducer const reducer = (state = initState, action) = > {... . }Copy the code

Reducer for pure functions

A function that takes two arguments, A and B, and returns the new value of A based on B.

Remember the 4 Nos:
No surprises. No side effects. No API calls. No mutations. Just a calculation.
No surprises, no side effects, no API calls, no changes to passed parameters. It’s just a calculation.

Pure functions are the concept of functional programming that must abide by the following constraints:

  • Cannot overwrite parameters
  • The WRITE I/O API cannot be called
  • You cannot call impure methods such as date.now () or math.random () because you get different results each time

Reducer is a pure function, so the same state can be guaranteed and the same View must be obtained. The Reducer function cannot change the state and must return a new object.

A reducer function can have many reducer files, so have an index.js as the “governor file”

Dispatch and action

The only way to change state is to dispatch an action

store.disptch()

action

  • Action is a payload of information sent from the APP (logic layer, view layer) to your Store (data layer).
  • Action is the only source of information for the Store.
  • Actions need to be dispatched by the dispatch() function.
  • Actions are pure, flat JavaScript objects.
  • An action must have a type attribute. The type attribute indicates what the action does.

An action is a JSON with a type attribute:

{"type" : "ADD"}
Copy the code

Payload load

The action has not only a type property, but other properties called payloads.

CombineReducers merges multiple reducer

Different businesses are put into a number of standard reducer, and finally merged with redux.combineReducer().

Note:

  • Multiple namespaces when accessing values
  • When changing values, there is no namespace
Merge the reducer because there can only be one reducer for any project. const reducer = redux.combineReducers({ counterReducer , studentReducer }); // Store, no matter how big the project is, there must be only one store Console.log (store.getState().counterreducer.a); // However, when changing the value, there is no namespace store.dispatch({"type" : "ADD"}); store.dispatch({ "type" : "ADD"}); store.dispatch({ "type" : "ADD"}); Console.log (store.getState().counterreducer.a);Copy the code

React and Redux work together

All data is stored in the Store

Configuration and Use

  1. Install the webPack + React dependencies first
npm install --save redux
npm install --save react-redux
Copy the code
  • React-redux is the official ‘glue’
    • This binder provides two things: a Provider component and a connect function.
  1. Provider from react-redux

main.js

import React from "react"; import ReactDOM from "react-dom"; import {createStore} from "redux"; import {Provider} from "react-redux"; import App from "./App"; import reducer from "./reducers"; Const store = createStore(reducer); ReactDOM.render( <Provider store={store}> <App></App> </Provider> , document.getElementById("app") );Copy the code

app.js

  • import { connect } from “react-redux”
import React, { Component } from 'react'; import { connect } from "react-redux"; class App extends Component { constructor(){ super(); } to render () {return (< div > < h1 > root component {this. Props. A} < / h1 > < button onClick = {() = > {this. Props. The add (); App export default connect(({counterReducer}) => ({a: </button> </div>)) counterReducer.a }), (dispatch) => ({ add(){ dispatch({"type" : "ADD"}) } }) )(App);Copy the code

Provider

  • Providers are components that are used once in the main.js entry file
  • Connect is a function, which component needs to “connect” data, which component needs to connect to decorate.
  • The mechanism of providers is to use the context context mechanism.

Provider is easy to use. After wrapping the package, wrap the app. Note the Store property:

import {Provider} from "react-redux";

ReactDOM.render(
    <Provider store={store}>
        <App></App>
    </Provider>
    ,
    document.getElementById("app")
);
Copy the code

Connect a decorator

Grammar:

Connect (mapStateToProps, mapDispatchToProps)Copy the code
  • There are only two ways for a component to update its view:
    • The component’s own state changes
    • Changes to the props of the passed component
  • The global Store data has changed and the component view needs to be updated.
  • The data in the store, to be “decorated” on the component, becomes the props of the component.

The component should be decorated with connect()() to expose:

  • The first () says how to decorate, and the second () says who to decorate.
    • The first () has two parameters mapStateToProps and mapDispatchToProps

MapStateToProps (State, ownProps)

  • MapStateToProps is a function that maps a component to the state of a store. It passes in two parameters and returns an object.
  • MapStateToProps does not need to be passed. If not, the component does not listen for store changes, meaning store updates do not cause UI updates.
export default connect(
    ({counterReducer}) => ({
        a : counterReducer.a
    })
)(App);
Copy the code

The reducer name is listed in the parameters of this function. To wrap the reducer with curly braces, the return value of the function is an object, so there must be a pair of small brackets.

All keys of this returned object will be props for the component.

<h1> Root component {this.props. A}</h1>Copy the code

mapDispatchToProps

MapDispatchToProps is used to map components to store.dispatch, either as an objeft or as a function

export default connect(
    ({counterReducer}) => ({
        a: counterReducer.a
    }),
    (dispatch) => ({
        add(){
            dispatch({"type" : "ADD"})
        }
    })
)(App);
Copy the code

Logger — Installation of the output

  • One installation, one lead, one installation dependency
npm install --save redux-logger
Copy the code

Configuration in main.js

import React from "react"; import ReactDOM from "react-dom"; import {createStore , applyMiddleware} from "redux"; import {Provider} from "react-redux"; import logger from "redux-logger"; import App from "./App"; import reducer from "./reducers"; Const store = createStore(Reducer, applyMiddleware(logger)); ReactDOM.render( <Provider store={store}> <App></App> </Provider> , document.getElementById("app") );Copy the code

From now on, you can see the console’s automatic output on any dispatch: you can see the state before the change, the action that was sent, and the state after the change.