一、简介
在 react 开发的项目中,组建直接传递参数或者事件都需要props一层层代理,对于复杂组件,它可能嵌套的子组件非常多,层级也比较深,那么,如果还采用props链条来维护组件通信或者数据共享,将非常困难,也不利于开发和维护。
所以,当有多个组件需要共享状态/数据时,可以使用官方的一个状态管理库 react-redux,
从一开始的 Flux ,演变成 Redux ,而 Redux 并不是专为 React 开发的,它可以应用在任何框架上,而 react-redux 的出现, 是为了在 react 中更好的使用它。
二、概念
2.1、UI 组件
- 只负责 UI 的呈现,不带有任何业务逻辑
- 没有状态(即不使用
this.state这个变量) - 所有数据都由参数
(this.props)提供 - 不使用任何
Redux的API
2.2、容器组件
- 负责管理数据和业务逻辑,不负责 UI 的呈现
- 带有内部状态
- 使用
Redux的API
2.3、connect()
React-Redux 提供connect方法,用于从 UI 组件生成容器组件。connect 的意思,就是将这两种组件连起来。
三、基本使用
以一个计数器为例
编写一个 UI 组件,用 connect 方法将其生成容器组件。
3.1 组件
src/container/Counter/index.js
1 | import React, { Component } from "react"; |
3.1.1 bindActionCreators
Redux 中的 bindActionCreators,是通过 dispatch 将 action 包裹起来,这样可以通过 bindActionCreators 创建的方法,直接调用dispatch(action)(隐式调用)。
1 | import { bindActionCreators } from 'redux'; |
3.2 action
在容器组件中使用 dispatch 向外请求一个 action ,type 字段是必须要有的,类似于后端的接口 url 地址
src/container/Counter/action.js
1 | export function handleIncreaseAction(num) { |
3.2.1 规范
在 action 中定义的 type ,最好使用常量定义,供 reduce 直接调入使用。
action
1 | export const INCREMENT_COUNTER = 'INCREMENT_COUNTER'; |
reducer
1 | import { INCREMENT_COUNTER, DECREMENT_COUNTER } from '../actions/counter'; |
3.3 reducer
在 reducer 中对数据进行修改操作
src/container/Counter/reducer.js
1 | const counterReducer = (state = { count: 0 }, action) => { |
3.4 组合所有的 reducer
src/reducers.js
1 | import { combineReducers } from "redux"; |
3.5 创建 store
src/configureStore.js
1 | import { createStore } from "redux"; |
3.6 <Provider> 组件
使用 React-Redux 提供 Provider 组件,可以让容器组件拿到 state。
src/index.js
1 | import React from "react"; |
四、调试
在开发的过程中,为了更加方便地实时查看到 state 状态,可以使用 redux-devtools-extension
1 | // compose 用来组和插件和中间件 |
在谷歌应用商店中下载 redux-devtools 插件
效果图
Redux 入门教程(三):React-Redux 的用法 — 阮一峰