React Foundation Consolidation (31) - Store Data Subscription and Redux Optimization
1. Subscription of store data
-
store/index.js
const { createStore } = require("redux"); // 初始化数据 const initialState = { name: "test", title: "hello redux", }; function reducer(state = initialState, action) { // 采用switch 替代 if switch (action.type) { case "change_name": return { ...state, name: action.name, }; // case / return default: return state; } } // 创建的store const store = createStore(reducer); module.exports = store;
-
test.js
const store = require("./store"); // 采用订阅方式 const unsubscribe = store.subscribe(() => { console.log("subscribe:", store.getState()); }); // 使用action修改store中的数据 store.dispatch({ type: "change_name", name: "change name test", }); store.dispatch({ type: "change_name", name: "change name test111", }); unsubscribe();
2. Optimization of Redux
- Redux code optimization:
- Put the dispatched action generation process into an actionCreators function
- Put all the defined actionCreators functions into a separate file: actionCreators.js
- The use of string constants in actionCreators and reducer functions is consistent, so the constants are extracted into a separate constants.js file
- Put the reducer and the default value (initialState) in a separate reducer.js file
-
test.js
const store = require("./store"); const { changeNameAction } = require("./store/actionCreators"); // 采用订阅方式 const unsubscribe = store.subscribe(() => { console.log("subscribe:", store.getState()); }); // 使用action修改store中的数据 store.dispatch(changeNameAction("change name test")); store.dispatch(changeNameAction("change name test111")); unsubscribe();
-
store/index.js
const { createStore } = require("redux"); const reducer = require("./reducer") // 创建的store const store = createStore(reducer); module.exports = store;
-
store/actionCreators.js
const { CHANGE_NAME } = require("./constants"); // actionCreators: 帮助我们创建action const changeNameAction = (name) => { return { type: CHANGE_NAME, name, }; }; module.exports = { changeNameAction, };
-
store/constants.js
const CHANGE_NAME = "change_name"; module.exports = { CHANGE_NAME, };
-
store/reducer.js
const { CHANGE_NAME } = require("./constants"); // 初始化数据 const initialState = { name: "test", title: "hello redux", }; // 定义reducer函数:纯函数 // 两个参数: // 1.store中上一次的值; // 2.本次需要更新的action // 返回值:它的返回值会作为sto re之后存储的state function reducer(state = initialState, action) { console.log("reducer:", state, action); // 有新数据进行更新的时候,那么返回一个新的state switch (action.type) { case CHANGE_NAME: return { ...state, name: action.name, }; // case / return default: return state; } // 若没有新数据更新,返回之前的state // return state; } module.exports = reducer;
-
operation result