concept
redux is an architecture mode, which can be used in combination with react and vue.
Problems solved
Modify the shared data state gracefully to avoid unnecessary (difficult to eliminate) problems caused by the cascading changes of parent-child components (it is troublesome to change if there are many child components) and external changes. Therefore, all changes are modified by one method (dispatch).
Implementation steps
//Data after state and action function reducer (state, action) { /!* Initialization state and switch case *!/ } // Get state through reducer // Implementation of action // Monitor data changes const store = createStore(reducer) // Listen for data changes and re render the page // Monitor data change through observer mode to avoid frequent rendering without state change store.subscribe(() => renderApp(store.getState())) // Render page for the first time renderApp(store.getState())
Example
const usersReducer = (state, action) => { if (!state) return []; switch (action.type) { case "ADD_USER": return [...state, action.user] case "DELETE_USER": return [...state.slice(0, action.index), ...state.slice(action.index + 1)] case "UPDATE_USER": let user = { ...state[action.index], ...action.user, } return [ ...state.slice(0, action.index), user, ...state.slice(action.index + 1), ] default: return state } } //State and dispatch are encapsulated function createStore (reducer) { let state = null const listeners = [] const subscribe = (listener) => listeners.push(listener) const getState = () => state const dispatch = (action) => { state = reducer(state, action) // Overwrite the original object // console.log(listeners) listeners.forEach((listener) => { // console.log(listener) listener() }) } dispatch({}) // Initialize state return { getState, dispatch, subscribe } } const store = createStore(usersReducer); console.log(store.getState()); //increase store.dispatch({ type: 'ADD_USER', user: { username: 'Lucy', age: 12, gender: 'female' } }); console.log(store.getState()); //change store.dispatch({ type: 'UPDATE_USER', index: 0, user: { username: 'Tomy', age: 12, gender: 'male' } }); console.log(store.getState()); //Delete store.dispatch({ type: 'DELETE_USER', index: 0 // Delete specific subscript user }); console.log(store.getState());
Reference React.js