本文主要记录redux、以及react-redux的基础用法
一、redux
1.1 简介
(1)概念
- 是一个专门用来做
状态管理的js库(不是react插件) - 可以用在
vue、react、angular项目中,但基本与react配合使用 - 作用:集中式管理react应用中的多个组件共享的状态
(2)什么情况下需要使用redux
- 某个组件的状态,需要让其他组件可以随时拿到(
共享) - 一个组件需要改变另一个组件的状态(
通信) - 总体原则:能不用就不用,如果不用比较吃力才用
1.2 工作流程
redux工作流程图如下:
三个核心概念:
(1)action
-
动作的对象
-
包含两个属性
type:属性标识,值为字符串,唯一,必要属性data:数据属性,值任意类型,可选属性- 例子
{type:'ADD_STUDENT', data: {name: 'tom', age: '18'}}(2)reducer
-
用于
初始化、加工状态 -
加工时,根据旧的state和action,产生新的state的
纯函数
(3)store
- 将
state、action、reducer联系在一起的对象 - 加工时,根据旧的state和action,产生新的state的纯函数
目录结构
│ └─ store
│ ├─ actions // actions,文件夹内以模块区分
│ │ ├─ count.js
│ │ └─ person.js
│ ├─ constants.js // action type唯一标识常量
│ ├─ index.js // 入口文件
│ └─ reducers // reducers,文件夹内以模块区分
│ ├─ conut.js
│ ├─ index.js // reducers统一暴露文件,合并reducers
│ └─ persons.js
1.3 store
引入createStore,专门用于创建redux中最为核心的store对象,而redux-thunk、applyMiddleware用于支持异步action,后文会讲到什么是异步action
js
复制代码
// src/store/index.js
import { createStore, applyMiddleware } from "redux";
// 用于支持异步action
import thunk from "redux-thunk";
import reducers from "./reducers";
export default createStore(reducers, applyMiddleware(thunk));
1.4 action
定义action对象中type类型的常量值,消除魔法字符串
// src/store/constants.js
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
创建action,普通action返回对象,异步action返回函数
// src/store/actions/count.js
import { INCREMENT, DECREMENT } from "../constants";
// 普通action的值为object `{type: INCREMENT, data }`
export const increment = data => ({ type: INCREMENT, data });
export const decrement = data => ({ type: DECREMENT, data });
// 异步action的值为函数
export const incrementAsync = (data, time) => {
return (dispatch) => {
setTimeout(() => {
dispatch(increment(data));
}, time);
};
};
异步action
- 延迟的动作不想交给组件本身,想交给action
- 何时需要异步action:想要对状态进行操作,但是具体的数据考异步任务返回
异步action不是必须要写的,完全可以自己等待异步任务的结果再去分发同步action
创建的action不再返回一个对象,而是一个函数,等异步任务有结果后,一般再去分发一个同步的action去真正操作数据
1.5 reducer
reducer函数会接到两个参数,分别为:之前的状态(preState),动作对象(action)- 从
action对象中获取type,data - 根据
type决定如何加工数据
js
复制代码
import {INCREMENT, DECREMENT} from '../constants'
// 初始化状态
const initState = 0;
export default function count(preState = initState, action) {
const { type, data } = action;
switch (type) {
case INCREMENT:
return preState + data;
case DECREMENT:
return preState - data;
default:
return preState;
}
}
(1)初始化状态
在reducer里面没有设置初始值时,console.log(preState, action),在控制台如下图可以看到输出的preState=undefined,type=@@redux/INITq.p.v.o.d.w
type redux内部处理为随机值,每次输出的都不一样
通过
const initState = 0;export default function count(preState = initState, action) {....default: return preState;}设置初始值
(2)reducer是一个纯函数
// src/store/reducers/persons.js
import { ADD_PERSON } from "../constants";
const initState = [{ id: "001", name: "jona", age: "23" }];
export default function persons(preState = initState, action) {
const { type, data } = action;
switch (type) {
case ADD_PERSON:
// return preState.unshift(data) // 此处不可以这样写,这样会导致preState被改写了,personReducer就不是纯函数了,redux识别不到状态改变,视图不会更新了
return [data, ...preState];
default:
return preState;
}
}
(3)合并reducers
通过combineReducers合并,接收的参数是一个对象,对象的key值与getState()得到的对象的key一致
// src/store/reducers/index.js
import { combineReducers } from "redux";
import count from "./conut";
import persons from "./persons";
export default combineReducers({
count,
persons,
});
1.6 getState、dispatch
- 组件通过
getState()拿store的数据 - 通过
dispatch触发状态更新
jsx
复制代码
import store from "../../store";
import { increment } from "../../store/action/count";
// 加法
clickIncrement = () => {
const { value } = this.selectNumber;
store.dispatch(increment(value * 1));
};
render() {
return (
<div>
<h1>当前求和为: {store.getState()}</h1>
...
<button onClick={this.clickIncrement}>+</button>
</div>
)
}
视图不更新问题
dispatch后,发现store的值已经变化了但是视图不更新,redux内部不支持自动更新,需要通过subscribeAPI监听redux中状态变化,只有变化,就需要重新调用render
componentDidMount() {
store.subscribe(() => {
this.forceUpdate();
});
}
二、react-redux
2.1. react-redux VS redux
为了方便使用,Redux 的作者封装了一个 React 专用的库 React-Redux 这两个仓库的区别如下:
- redux需要监听store变化更新视图,利用
store.subscribe(() => { this.forceUpdate(); });react-redux不需要监听
2.2、connect()、mapStateToProps
React-Redux提供connect方法,用于从UI组件生成容器组件
connect方法接受两个参数:mapStateToProps和mapDispatchToProps。它们定义了 UI 组件的业务逻辑。前者负责输入逻辑,即将state映射到 UI 组件的参数(props),后者负责输出逻辑,即将用户对 UI 组件的操作映射成 Action
mapStateToProps 接收 state 参数,mapDispatchToProps 接收 dispatch 参数
// 容器组件
import { connect } from "react-redux";
import CountUI from "../../components/count";
import {
createIncrementAction,
createDecrementAction,
createIncrementAsyncAction,
} from "../../redux/count_action";
const mapStateToProps = (state) => ({ count: state });
const mapDispatchToProps = (dispatch) => ({
increment: (number) => {
dispatch(createIncrementAction(number));
},
incrementAsync: (number) => {
dispatch(createIncrementAsyncAction(number, 500));
},
decrement: (number) => {
dispatch(createDecrementAction(number));
},
});
export default connect(mapStateToProps, mapDispatchToProps)(CountUI);
// UI组件
import React, { Component } from "react";
export default class CountUI extends Component {
// 加法
increment = () => {
const { value } = this.selectNumber;
this.props.increment(value * 1);
};
// 减法
decrement = () => {
const { value } = this.selectNumber;
this.props.decrement(value * 1);
};
// 奇数加
incrementIfOdd = () => {
if (this.props.count % 2 === 1) {
const { value } = this.selectNumber;
this.props.increment(value * 1);
}
};
// 异步加
incrementAsync = () => {
const { value } = this.selectNumber;
this.props.increment(value * 1);
};
render() {
return (
<div>
<h1>当前求和为: {this.props.count}</h1>
...
</div>
);
}
}
2.3、mapDispatchToProps
mapDispatchToProps是connect函数的第二个参数,用来建立 UI 组件的参数到store.dispatch方法的映射。也就是说,它定义了哪些用户的操作应该当作 Action,传给 Store
它可以是一个函数,也可以是一个对象
(1)如果mapDispatchToProps是一个函数
// 容器组件
const mapDispatchToProps = (dispatch) => ({
increment: (number) => {
dispatch(createIncrementAction(number));
},
incrementAsync: (number) => {
dispatch(createIncrementAsyncAction(number, 500));
},
decrement: (number) => {
dispatch(createDecrementAction(number));
},
});
// mapDispatchToProps的一般写法,返回function
export default connect(mapStateToProps, mapDispatchToProps)(CountUI);
(2)如果mapDispatchToProps是一个对象
键值是一个函数, Action creator ,返回的 Action 会由 Redux 自动发出
// mapDispatchToProps的简写,返回object
export default connect(mapStateToProps, {
increment: createIncrementAction,
incrementAsync: createIncrementAsyncAction,
decrement: createDecrementAction,
})(CountUI);
2.5、Provider
connect方法生成容器组件以后,需要让容器组件拿到state对象,才能生成 UI 组件的参数。
一种解决方法是将state对象作为参数,传入容器组件。但是,这样做比较麻烦,尤其是容器组件可能在很深的层级,一级级将state传下去就很麻烦。
// src/App.js
import React, { Component } from "react";
import Count from "./container/count";
import store from "./redux/store";
export default class App extends Component {
render() {
return <Count store={store} />;
}
}
React-Redux 提供Provider组件,可以让容器组件拿到state
Provider在根组件外面包了一层,这样一来,App的所有子组件就默认都可以拿到state了
它的原理是
React组件的context属性
使原来整个应用成为
Provider的子组件 接收Redux的store作为props,通过context对象传递给子孙组件上的connect
// src/index.js
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import store from './redux/store'
import App from "./App";
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);