redux浅谈

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cjg214/article/details/83240513

// 1.创建store(导入createStore;传入reducer)

import { createStore } from 'redux';

function counter(state = 0, action) {
  switch (action.type) {
    case "INCREMENT":
      return state + 1;
    case "DECREMENT":
      return state - 1;
    default:
      return state;
  }
}

const store = createStore(counter);

// 2.获取状态、监听变化、发起action更新状态

let curVal = store.getState();// 获取

const listener = () => {
  const previousVal=curVal;
  curVal=store.getState();
  console.log("pre state",previousVal,"next state",curVal);
}

store.subscribe(listener);// 注册监听器

store.dispatch({type:"INCREMENT"});// 发起action
store.dispatch({type:"DECREMENT"});

备注:

store的三个方法

getState()

dispatch(action)

subscribe()

猜你喜欢

转载自blog.csdn.net/cjg214/article/details/83240513