I’m going to share my handwritten notes on redux, so you can understand what REdux is all about, because front-end engineers say,
The difference between a primary front-end and an intermediate front-end is understanding design patterns and object orientation
This is a split of the redux idea. Redux was split into five parts, and the final result was react Redux.
Why react Redux?
With redux, state is no longer something anyone can call setState to modify,
React does not have redux and does have Redux
React: Use setState to modify state data and then render;
React-redux: Determines whether to execute setState through dispatch. If the dispatch check passes, the setState function will be executed. Otherwise, the setState function will not be executed.
1. Introduce dispatch to manage calls to setState
<div id="title"></div>
<div id="contents"></div> <script> // render modulefunction render() {
document.getElementById('title').innerHTML = state.title;
document.getElementById('contents').innerHTML = state.content; } var state = {title:'New title',
content: 'New content'} // Render (); // Change data module ** Trigger data rendering after changefunction setState(newState) { this.state = { ... state, ... newState } render() } </script>Copy the code
The following part is the embodiment of redux idea. The parameter type can be judged by dispath, and setState can be called only when it is legal
<script> // management module, to trigger data changes please execute this function, and give the specifiedtypeOtherwise, the command is not executedsetState
var dispatch = function (action) {
switch (action.type) {
case 'CHANGE_TITLE'// It was senttypeThe right tosetState
setState({
title: action.newTitle
})
break;
default:
break; }} // Modify the data to call the dispatch function, only inside the JSONtypeThe corresponding can be executed only after the dispatch detectionsetState
dispatch(
{
type: 'CHANGE_TITLE',
newTitle: 'I'm a new title allowed to change by the dispatch function'
}
)
</script>
Copy the code
2. The introduction of the subscriber
<div id="title"></div>
<div id="contents"></div>
<script>
function render() {
document.getElementById('title').innerHTML = state.title;
document.getElementById('contents').innerHTML = state.content;
}
var state = {
title: 'New title',
content: 'New content'
}
render()
Copy the code
Create listeners by introducing a subscriber function that pushes new events into the array, such as the render function, and executes the functions in the listensers array after successfully triggering setState.
var dispatch = function (action) {
switch (action.type) {
case 'CHANGE_TITLE': state = { ... state, title:action.newTitle }break;
default:
break; } listeners. ForEach (e=>e()) // Put this arraysetThe event executed after State, var subscribe =functionSubscriber (listener){subscribe(listener)} subscribe(render) //type: 'CHANGE_TITLE',
newTitle: 'I'm a new title allowed to change by the dispatch function'
}
)
</script>
</body>
Copy the code
3. Initially encapsulate createStore
div id="title"></div>
<div id="contents"></div> <script> // render functionfunction render(state) {
document.getElementById('title').innerHTML = state.title;
document.getElementById('contents').innerHTML = state.content;
}
//store 核心部分
var createStore = function() {//state data var state = {title:'This is a title.',
content: 'This is a piece of content.'Function listeners = []; Var getState =function () {
returnstate; } / / dispatch monitoringtypeIf it's legal, it's legalsetState function var dispatch =function (action) {
switch (action.type) {
case 'CHANGE_TITLE': state = { ... state, title: action.newTitle }break;
default:
break; } listeners. ForEach (e => e())function(Listener) {listeners. Push (listener)} // Expose the call interfacereturn{dispatch, subscribe, getState}} // call part // create an instantiation object var store = createStore(); Var {subscribe, dispatch, getState} = store; // Subscribe (() => render(getState())); // Request dispatch to change state dispatch({type: 'CHANGE_TITLE',
newTitle: 'I'm a new title allowed to change by the dispatch function'
}
)
render(getState())
</script>
Copy the code
However, the createStore function is impure, with predetermined state and Dispatch. The next step is to purify the function.
4. Purification of createStore function, separate createStore from state and setState, and put state and setState into appReducer function
<div id="title"></div>
<div id="contents"></div> <script> //storefunction() {// Set state to null; var state = null var listeners = []; var dispatch =functionState = appReducer(state, action); listeners.forEach(e => e()); } // Call Dispatch to initialize state and get the default state in appReducer. dispatch({}) var subscribe =function (listener) {
listeners.push(listener)
}
var getState = function () {
returnstate; } // Expose the interfacereturn {
dispatch,
subscribe,
getState
}
}
var appReducer = function(state, action) {// Initializes state in store // because state initializes nullif(! state) {return {
title: 'This is a title.',
content: 'This is a piece of content.'}} state switch (action.type) {case 'CHANGE_TITLE':
return {
...state,
title: action.newTitle
}
break;
default:
return state;
}
}
var store = createStore();
var { subscribe, dispatch, getState } = store;
subscribe(() => render(getState()))
dispatch(
{
type: 'CHANGE_TITLE',
newTitle: 'I'm a new title allowed to change by the dispatch function'})function render(state) {
document.getElementById('title').innerHTML = state.title;
document.getElementById('contents').innerHTML = state.content; } // render(getState()) </script>Copy the code
CreateStore is still not a pure function and cannot stand on its own because of the execution of the dead appReducer function.
5. Make createStore pure once and for all, with appReducer passed into createStore as a parameter.
// Now is a very clean pure functionfunction createStore(appReducer) {
state = null;
var listeners = [];
function dispatch(action) {
state = appReducer(state, action)
listeners.map(e => e())
}
dispatch({})
function getState() {
return state
}
function subscribe(listener) {
listeners.push(listener);
}
return{dispatch, getState, subscribe}} // appReucer functionfunctionAppReducer (state, action)if(! state) {return {
title: 'hello',
content: 'Welcome'
}
}
switch (action.type) {
case 'CHANGE_TITLE':
return {
...state,
title: action.newTitle
}
break;
default:
break; Var store = createStore(appReducer); var { dispatch, getState, subscribe } = store; subscribe(() => render(getState())) dispatch( {type: "CHANGE_TITLE",
newTitle: 'I'm a new title allowed to change by the dispatch function'})function render(state) {
document.getElementById('title').innerHTML = state.title;
document.getElementById('content').innerHTML = state.content;
}
render(getState());
Copy the code
React Redux: React Redux: React Redux
Apply your createStore to React
Three interfaces to store:
Dispatch, change the state in store
Subscribe to render component’s event this.setState
GetState, get the state in the store
In this way, the component does not need to maintain its own state and instead uses state from an imported store
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
import createStore from './createStore';
let appReducer = (state, action) => {
if(! state) {return {
title: "This is the title.",
content: "This is the content."
}
}
switch (action.type) {
case "CHANGE_TITLE":
return {
...state,
title: action.newTitle
}
case "CHANGE_CONTENT":
return {
...state,
content: action.newContent
}
default:
returnstate; }} var store = createStore(appReducer) var store = createStore(appReducer)constructor() { super(); This.setstate store.subscribe(() => {this.setState(store.getState)})} _chengeTitle(newTitle) {this.setState(store.getState)} // Call Dispatch to change state in store, and then execute the events subscribed to by The Listeners array store.dispatch({type: "CHANGE_TITLE",
newTitle: newTitle
})
}
render() {
const { title, content } = store.getState();
{ console.info(store.getState()) }
return (
< div >
<h1>{title}</h1>
<p>{content}</p>
<button onClick={() => this._chengeTitle('You clicked the button, the title has been changed'}} reactdom.render (<App />, document.getelementbyId ())'root'));
serviceWorker.unregister();
Copy the code