Redux
介绍
Redux 是为React 提供的状态管理机制:
- Redux 将整个状态存储到一个地方 — store。
- 这个 store 中有个对象 state 用来存放数据
- 组件改变 state 数据的唯一方法是通过调用 store.dispatch 方法,触发一个action。这个 action 相当于一个指令,是一个对象,里面的 type 属性相当于一个指令(是必须的)。
- reducer 会处理相应的 action指令,处理完毕后,将数据返回给store,于是 state 完成更新。
- 其他组件可以通过订阅 store 中的 state 来刷新视图。
使用步骤
-
创建 action
组件想要更新 state 中的数据,就必须先触发 action 。可以理解为指令,它是一个对象,必须有一个 type 属性,定义 action 的类型。
-
创建 reducer
- reducer 是一个函数,接受旧的 state 和 action ,返回新的 state。
- 组件触发 action 指令,之后会将 state 放入reducer 中进行相应的加工,并返回新的 state。
-
创建 store, 使用 createStore 方法
- store 可以理解为总工厂。
- store 提供 subscribe(订阅)、dispatch(触发action) 、getState(获取state)这些方法。
实战
import { createStore } from "redux"; // 引入
const value = { count: 0 };
const reducer = (state = value, action) => {
switch (action.type) {
case "INCREASE":
return { count: state.count + 1 };
case "DECREASE":
return { count: state.count - 1 };
default:
return state;
}
};
const actions = {
increase: { type: "INCREASE" },
decrease: { type: "DECREASE" }
};
const store = createStore(reducer);
store.subscribe(() => console.log(store.getState()));
store.dispatch(actions.increase); // {count: 1}
store.dispatch(actions.increase); // {count: 2}
store.dispatch(actions.increase); // {count: 3}
redux 工作流图 :
React-Redux
redux 是用来管理数据的,react-redux 可以说是用来连接组件与store中心,即把react 与 redux 联系起来。
react-redux 提供两个方法: Provider 和 connect
connect
connect 方法用于连接 React 组件与 Redux store ,连接操作不会改变原来的组件,而是返回一个新的已经与 Redux store 连接的组件。
connect(mapStateToProps, mapDispatchToProps,mergeProps,options)(MyComponent)
前面两个参数用的多:
- mapStateToProps 函数接收整个 Redux store 的 state 作为 props,然后返回一个传入到组件 props 的对象。(就是将 Redux 中的 state 映射到 props 中去)
- mapDispatchToProps :(不传,默认是dispatch)返回一个对象,也会作为 props 中的属性。用来绑定响应事件
Provider
一般将顶级组件包裹在 Provider 组件中,将store 作为参数放到 Provider 组件中去,使得每个组件都能访问 Redux 中的数据。
<Provider store={store}>
<App />
</Provider>
实战
- 推荐博文: redux