redux
Introduction:
Redux is a JavaScript state container that provides predictable state management. (If you need a WordPress Framework, check out Redux Framework.)
Allows you to build consistent applications that run in different environments (client, server, native application) and are easy to test. Not only that, it also provides a great development experience, such as a time travel debugger that can be edited in real time.
Redux also supports other interface libraries in addition to React. It is small and lean (only 2kB, including dependencies).
Website: www.redux.org.cn/
Nguyen one redux tutorial: www.ruanyifeng.com/blog/2016/0…
Derived using
// import { createStore } from 'redux'
import { createStore } from './util/store.js'
import { applyMiddleware } from 'redux'
import logger from 'redux-logger'
import thunk from 'redux-thunk'
function countReducer(state = 0, action) {
switch (action.type) {
case 'ADD':
return state + 1
case 'MINUS':
return state - 1
default:
return state
}
}
const store = createStore(countReducer, applyMiddleware(thunk, logger))
// applyMiddleware(thunk, Logger) supports passing in functions to operate and logging
export default store
Copy the code
Page using
import React, { Component } from 'react'
import store from './store'
export default class ReduxPage extends Component {
componentDidMount() {
store.subscribe(() = > {
this.forceUpdate()
})
}
add = () = > {
store.dispatch({
type: 'ADD'
})
}
minus = () = > {
store.dispatch({
type: 'MINUS'
})
}
asyAdd = () = > {
// It is possible to pass in a function // to get dispatch, getState
store.dispatch((dispatch, getState) = > {
setTimeout(() = > {
console.log('now ', getState()) //sy-log
dispatch({ type: 'ADD'})},1000)})}render() {
console.log('store', store) //sy-log
return (
<div>{'}<h3>ReduxPage</h3>
<p>{store.getState()}</p>
<button onClick={this.add}>add</button>
<button onClick={this.minus}>minus</button>{/ *<button onClick={this.minus}>minus</button>* / {'}}<button onClick={this.asyAdd}>asyAdd</button>{'}</div>)}}Copy the code
Principle of the store. Js
export default function createStore(reducer, enhancer) {
if (enhancer) { / / the plugin
return enhancer(createStore)(reducer) // In the next chapter
}
let currentState // Store the initial value
let currentListeners = []
function getState() {
return currentState
}
function dispatch(action) {
currentState = reducer(currentState, action)
currentListeners.forEach((listener) = > listener())
return action
}
function subscribe(listener) {
currentListeners.push(listener)
return () = > {
const index = currentListeners.indexOf(listener)
currentListeners.splice(index, 1)
}
}
dispatch({
type: 'init'
})
return {
getState,
dispatch,
subscribe
}
}
Copy the code