特别提示==> 这仅仅是个人的学习笔记,想要了解更多请读原著一篇文章总结redux、react-redux、redux-saga
什么是Redux
- 为了给React应用提供状态管理
- Redux会将整个应用的状态数据存到一个地方 -- store
- 这个store 里面保存 一颗状态树:state tree
- 组件改变state的唯一方法是通过调动store的dispatch方法,触发一个action,这个这个action会被对应的reducer处理,返回一个新的state,从而完成state的更新
- 组件是通过派发行为(dispatch action)给store,而不是直接传值给其他组件
- 其他组件需要通过订阅store中的状态(state)来刷新自己的视图
基本使用
npm install redux -S // 安装
import { createStore } from 'redux' // 引入
//1. 创建reducer
const reducer = (state = {count: 0}, action) => {----------> ⑴
switch (action.type){
case 'INCREASE': return {count: state.count + 1};
case 'DECREASE': return {count: state.count - 1};
default: return state;
}
}
//2. 创建action
const actions = {---------->⑵
increase: () => ({type: 'INCREASE'}),
decrease: () => ({type: 'DECREASE'})
}
//3. 创建的store,使用createStore方法
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}
react-redux
把store直接集成到React应用的顶层props里面,只要各个子组件能访问到顶层props就行。这就是react-redux
<顶层组件 store={store}>
<App />
</顶层组件>
react-redux两个核心
- Provider
一般将顶级组件(这里是
<App/>),包裹在Provider中,这样app中的所有子组件都能被react-redux控制
这个组件的目的是让所有组件都能够访问到Redux中的数据。
<Provider store = {store}>
<App />
<Provider>
顶级组件。
- connect 核心代码
connect(mapStateToProps, mapDispatchToProps)(MyComponent)
mapStateToProps
把state映射到props中去 ,其实也就是把Redux中的数据映射到React中的props中去。 eg:简单例子
//先映射
const mapStateToProps = (state) => { return {
// prop : state.xxx | 意思是将state中的某个数据映射到props中
foo: state.bar }
}
//再使用(渲染)
class Foo extends Component {
constructor(props){
super(props);
}
render(){
return(
// 这样子渲染的其实就是state.bar的数据了
<div>this.props.foo</div>
)
}
}
Foo = connect()(Foo);
export default Foo;
mapDispatchToProps
把各种dispatch也变成了props让你可以直接使用
//先映射
const mapDispatchToProps = (dispatch) => { // 默认传递参数就是dispatch
return {
onClick: () => {
dispatch({
type: 'increatment'
});
}
};
}
//再使用(响应点击事件)
class Foo extends Component {
constructor(props){
super(props);
}
render(){
return(
//this.props.onClick,来调用dispatch,这样子就不需要在代码中来进行store.dispatch了
<button onClick = {this.props.onClick}>点击increase</button>
)
}
}
Foo = connect()(Foo);
export default Foo;
redux-saga
- 用于在redux中处理一些
异步操作 - 使用 createSagaMiddleware 方法创建 saga 的 Middleware ,然后在创建的 redux 的 store 时,使用 applyMiddleware 函数将创建的 saga Middleware 实例绑定到 store 上,最后可以调用 saga Middleware 的 run 函数来执行某个或者某些 Middleware 。
- 在 saga 的 Middleware 中,可以使用 takeEvery 或者 takeLatest 等 API 来监听某个 action ,当某个 action 触发后, saga 可以使用 call 发起异步操作,操作完成后使用 put 函数触发 action ,同步更新 state ,从而完成整个 State 的更新。