初次了解redux

December 18,2021

redux三个概念

store:负责管理所有全局的状态,真正管理数据的是state,它是一个纯js对象。

和store相关的几个函数
store.getState() 获取state
store.dispatch(action) action只有dispatch出去才能被reducer收到。用户点击按钮,产生一个action,store dispatch出去给所有的reducer
store.subscribe(listener) 监听store的变化,store有任何变化的时候调用callback listerner

reducer:实际去修改state,接受所有的action,根据action.type判断是不是需要操作

action:描述行为

{
    type: "PLUS_ONE",
    text: "Build my first Redux app"
 }

流程:

用户点击按钮=>形成一个action=>dispatch action给reducer=>reducer去生成一个新的state去替换旧的state


图片引用自:https://redux.js.org/tutorials/essentials/part-1-overview-concepts

(state+action) => new state state发生任何变化一定是action引起的。状态出了问题一定是action造成的,这种模式让问题更容易追踪。

几个封装的工具函数

1.combineReducers() 把多个reducer封装在一起

combineReducers({
  reducer1,
  reducer2
})

2. bindActionCreators创建action并且dispatch出去

demo

import { createStore, combineReducers, bindActionCreators } from "redux";
// init state
const initialState = { count: 1 };
// create reducer1
const counter = (state = initialState, action) => {
  switch (action.type) {
    case "PLUS_ONE":
      return { count: state.count + 1 };
    case "MINUS_ONE":
      return { count: state.count - 1 };
    case "CUSTOM_NUM":
      return { count: state.count + action.playload.count };
    default:
      break;
  }
  return state;
};
// create reducer2
const todos = (state = {}) => state;

// create store
const store = createStore(
  combineReducers({
    counter,
    todos
  })
);

// create action
function plusOne() {
  return {
    type: "PLUS_ONE",
    text: "plus one"
  };
}
function minusOne() {
  return {
    type: "MINUS_ONE",
    text: "minus one"
  };
}
function customCount(count) {
  return {
    type: "CUSTOM_NUM",
    text: "custom num",
    playload: { count }
  };
}
// 监听store的变化
store.subscribe(() => console.log(store.getState()));

// 把action dispatch出去
plusOne = bindActionCreators(plusOne, store.dispatch);
minusOne = bindActionCreators(minusOne, store.dispatch);
customCount = bindActionCreators(customCount, store.dispatch);

function run() {
  plusOne();
  minusOne();
  customCount(10);
}
export default function App() {
  return (
    <div>
      <button onClick={run}>Run</button>
      <p>* 请打开控制台查看运行结果</p>
    </div>
  );
}

codesandbox

上一篇 下一篇
Comments
Write a Comment