redux 基本使用 (1)

Redux使用非常简单

安装

npm i redux

基本使用

const redux = require('redux');

// 定义一个状态
let initialState = {
  count: 0
}

// 定义action来修改状态
const addAction = {type: 'ADD_COUNT', num: 1};
const subAction = {type: 'SUB_COUNT', num: -1};

// 使用reducer将状态和action关联起来
function reducer(state = initialState, action) {
  switch (action.type) {
    case 'ADD_COUNT':
      return {count: state.count + action.num};
    case 'SUB_COUNT':
      return {count: state.count + action.num};
    default:
      return state;
  }
}
// 创建 store
const store = redux.createStore(reducer);
  • 首先定义保存数据的  initialState 对象
  • 然后定义修改数据的  addAction 、 subAction 对象
  • 这两个对象只是  JavaScript 的普通对象,他们之间还需要借助一个  reducer 函数关联起来
  •  reducer 函数是接收两个参数  state (默认值是  initialState )和 action ,函数内部通过判断 action 来决定如何处理 state 
  • 最后我们调用  redux.createStore 函数并将 reducer 作为参数传递进去,返回一个对象  store 

 

获取  store 中的数据

store.getState(); // { count: 0 }
  • 调用  getState 函数可以获取  store 中的数据

修改  store 中的数据

store.dispatch(addAction);
  • 调用  dispatch 函数并将对应的  action 对象传递过去,  store 会根据这个 action 来修改数据

监听  store 的变化

store.subscribe(() => {
  console.log('store发生变化了', store.getState());
});
  • 通过  store 的  subscribe  函数来监听  store 的改变
posted @ 2021-12-03 16:43  霸哥yyds  阅读(287)  评论(0)    收藏  举报