Redux数据管理之store

store:用于保存数据,通过createStore()创建的对象。

该对象的成员:

  • dispatch:分发一个action
  • getState:得到仓库中当前的状态
  • replaceReducer:替换掉当前的reducer
  • subscribe:注册一个监听器,监听器是一个无参函数,该方法在分发一个action之后,会运行注册的监听器。该函数会返回一个函数,用于取消监听
// /src/redux/index.js
import { createStore } from 'redux';
import { createAddUserAction } from './action/users-action';
import reducer from './reducer';
import uuid from 'uuid';
const store = createStore(reducer);
console.log('store:', store);
store.subscribe(() => {
    console.log('1 状态改变了', store.getState());
});
store.subscribe(() => {
    console.log('2 状态改变了', store.getState());
});
console.log('old store:', store.getState()); // 得到仓库中当前的数据
store.dispatch(createAddUserAction({ id: uuid(), name: '用户3', age: 3 }));
console.log('new store:', store.getState()); // 得到仓库中当前的数据

subscribe监听函数运行时机

// /src/redux/index.js
import { createStore, bindActionCreators } from 'redux';
import {
    createAddUserAction,
    createDeleteUserAction,
} from './action/users-action';
import reducer from './reducer';
import uuid from 'uuid';
const store = createStore(reducer);
console.log('store:', store);
const unlisten = store.subscribe(() => { console.log('1 状态改变了', store.getState()); });
console.log('old store:', store.getState()); // 得到仓库中当前的数据
store.dispatch(createAddUserAction({ id: uuid(), name: '用户3', age: 3 }));
unlisten(); // 取消监听
store.dispatch(createDeleteUserAction({ id: 3 })); // 这段代码不会执行
console.log('new store:', store.getState()); // 得到仓库中当前的数据

subscribe取消监听