写在前面,大家好!我是【跨考菌】,一枚跨界的程序猿,专注于后台技术的输出,目标成为
全栈攻城狮
!这博客是对我跨界过程的总结和思考。如果你也对Java
、后端技术
感兴趣,抑或是正在纠结于跨界,都可以关注我的动态,让我们一起学习,一起进步~
我的博客地址为:【跨考菌】的博客
目录
上篇【React新手学习指南】06 小白也能看懂的React Router教程介绍了React Router路由的知识点,本文开始介绍React Redux的相关知识。和【跨考菌】一起加油吧~
如果你觉得对你有帮助的话,记得帮博主一键三连😊哦
1 Redux理解
1.1 学习文档
- 英文文档: https://redux.js.org/
- 中文文档: http://www.redux.org.cn/
- Github: https://github.com/reactjs/redux
1.2 Redux概述
- redux是一个独立专门用于做状态管理的JS库(不是react插件库)
- 它可以用在react, angular, vue等项目中, 但基本与react配合使用
- 作用: 集中式管理react应用中多个组件共享的状态
1.3 redux工作流程
1.4 什么情况下需要使用redux
- 总体原则: 能不用就不用, 如果不用比较吃力才考虑使用
- 某个组件的状态,需要共享
- 某个状态需要在任何地方都可以拿到
- 一个组件需要改变全局状态
- 一个组件需要改变另一个组件的状态
2 redux的核心API
2.1 createStore()
- 作用:
创建包含指定reducer的store对象 - 编码:
import {createStore} from 'redux'
import counter from './reducers/counter'
const store = createStore(counter)
2.2 store对象
- 作用:
redux库最核心的管理对象 - 它内部维护着:
state
reducer - 核心方法:
getState()
dispatch(action)
subscribe(listener) - 编码:
store.getState()
store.dispatch({type:'INCREMENT', number})
store.subscribe(render)
2.3 applyMiddleware()
- 作用:
应用上基于redux的中间件(插件库) - 编码:
import {createStore, applyMiddleware} from 'redux'
import thunk from 'redux-thunk' // redux异步中间件
const store = createStore(
counter,
applyMiddleware(thunk) // 应用上异步中间件
)
2.4 combineReducers()
- 作用:
合并多个reducer函数 - 编码:
export default combineReducers({
user,
chatUser,
chat
})
3 redux的三个核心概念:action、reducer、store
3.1 action
- 标识要执行行为的对象:crud
- 包含2个方面的属性
a. type: 标识属性, 值为字符串, 唯一, 必要属性
b. xxx: 数据属性, 值类型任意, 可选属性 - 例子:
const action = {
type: 'INCREMENT',
data: 2
}
- Action Creator(创建Action的工厂函数)
const increment = (number) => ({type: 'INCREMENT', data: number}
()代表对象的标识;
{}代表函数体的标识。
3.2 reducer
- 根据老的state和action, 产生新的state的纯函数
- 样例
export default function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + action.data
case 'DECREMENT':
return state - action.data
default:
return state
}
}
- 注意
a. 返回一个新的状态
b. 不要修改原来的状态(因为react内部是将老旧虚拟dom进行对比的,你不要改了,就无法对比了!!)
3.3 store
- 将state,action与reducer联系在一起的对象
- 如何得到此对象?
import {createStore} from 'redux'
import reducer from './reducers'
const store = createStore(reducer)
- 此对象的功能?
getState(): 得到state
dispatch(action): 分发action, 触发reducer调用, 产生新的state
subscribe(listener): 注册监听, 当产生了新的state时, 自动调用
4 使用redux编写应用
4.1 效果
4.2 下载依赖包
npm install --save redux
4.3 redux/action-types.js
/*
action对象的type常量名称模块
*/
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
4.4 redux/actions.js
/*
action creator模块
*/
import {INCREMENT, DECREMENT} from './action-types'
export const increment = number => ({type: INCREMENT, number})
export const decrement = number => ({type: DECREMENT, number})
4.5 redux/reducers.js
/*
根据老的state和指定action, 处理返回一个新的state
*/
import {INCREMENT, DECREMENT} from './action-types'
export function counter(state = 0, action) {
console.log('counter', state, action)
switch (action.type) {
case INCREMENT:
return state + action.number
case DECREMENT:
return state - action.number
default:
return state
}
}
4.6 components/app.jsx
/*
应用组件
*/
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import * as actions from '../redux/actions'
export default class App extends Component {
static propTypes = {
store: PropTypes.object.isRequired,
}
increment = () => {
const number = this.refs.numSelect.value * 1
this.props.store.dispatch(actions.increment(number))
}
decrement = () => {
const number = this.refs.numSelect.value * 1
this.props.store.dispatch(actions.decrement(number))
}
incrementIfOdd = () => {
const number = this.refs.numSelect.value * 1
let count = this.props.store.getState()
if (count % 2 === 1) {
this.props.store.dispatch(actions.increment(number))
}
}
incrementAsync = () => {
const number = this.refs.numSelect.value * 1
setTimeout(() => {
this.props.store.dispatch(actions.increment(number))
}, 1000)
}
render() {
return (
<div>
<p>
click {this.props.store.getState()} times {' '}
</p>
<select ref="numSelect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>{' '}
<button onClick={this.increment}>+</button>
{' '}
<button onClick={this.decrement}>-</button>
{' '}
<button onClick={this.incrementIfOdd}>increment if odd</button>
{' '}
<button onClick={this.incrementAsync}>increment async</button>
</div>
)
}
}
4.7 index.js
import React from 'react'
import ReactDOM from 'react-dom'
import {createStore} from 'redux'
import App from './components/app'
import {counter} from './redux/reducers'
// 根据counter函数创建store对象
const store = createStore(counter)
// 定义渲染根组件标签的函数
const render = () => {
ReactDOM.render(
<App store={store}/>,
document.getElementById('root')
)
}
// 初始化渲染
render()
// 注册(订阅)监听, 一旦状态发生改变, 自动重新渲染
store.subscribe(render)
4.8 问题
- redux与react组件的代码耦合度太高
- 编码不够简洁
5 react-redux
5.1 理解
- 一个react插件库
- 专门用来简化react应用中使用redux
5.2 React-Redux将所有组件分成两大类
- UI组件
a. 只负责 UI 的呈现,不带有任何业务逻辑
b. 通过props接收数据(一般数据和函数)
c. 不使用任何 Redux 的 API
d. 一般保存在components文件夹下 - 容器组件
a. 负责管理数据和业务逻辑,不负责UI的呈现
b. 使用 Redux 的 API
c. 一般保存在containers文件夹下
5.3 相关API
- Provider
让所有组件都可以得到state数据
<Provider store={store}>
<App />
</Provider>
- connect()
用于包装 UI 组件生成容器组件
import { connect } from 'react-redux'
connect(
mapStateToprops,
mapDispatchToProps
)(Counter)
- mapStateToprops()
将外部的数据(即state对象)转换为UI组件的标签属性
const mapStateToprops = function (state) {
return {
value: state
}
}
- mapDispatchToProps()
将分发action的函数转换为UI组件的标签属性
简洁语法可以直接指定为actions对象或包含多个action方法的对象
5.4 使用react-redux
- 下载依赖包
npm install --save react-redux - redux/action-types.js
不变 - redux/actions.js
不变 - redux/reducers.js
不变 - components/counter.jsx
/*
UI组件: 不包含任何redux API
*/
import React from 'react'
import PropTypes from 'prop-types'
export default class Counter extends React.Component {
static propTypes = {
count: PropTypes.number.isRequired,
increment: PropTypes.func.isRequired,
decrement: PropTypes.func.isRequired
}
increment = () => {
const number = this.refs.numSelect.value * 1
this.props.increment(number)
}
decrement = () => {
const number = this.refs.numSelect.value * 1
this.props.decrement(number)
}
incrementIfOdd = () => {
const number = this.refs.numSelect.value * 1
let count = this.props.count
if (count % 2 === 1) {
this.props.increment(number)
}
}
incrementAsync = () => {
const number = this.refs.numSelect.value * 1
setTimeout(() => {
this.props.increment(number)
}, 1000)
}
render() {
return (
<div>
<p>
click {this.props.count} times {' '}
</p>
<select ref="numSelect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>{' '}
<button onClick={this.increment}>+</button>
{' '}
<button onClick={this.decrement}>-</button>
{' '}
<button onClick={this.incrementIfOdd}>increment if odd</button>
{' '}
<button onClick={this.incrementAsync}>increment async</button>
</div>
)
}
}
- containters/app.jsx
/*
包含Counter组件的容器组件
*/
import React from 'react'
// 引入连接函数
import {connect} from 'react-redux'
// 引入action函数
import {increment, decrement} from '../redux/actions'
import Counter from '../components/counter'
// 向外暴露连接App组件的包装组件
export default connect(
state => ({count: state}),
{increment, decrement}
)(Counter)
/**
* 解释:
* 上面的理解:
* 其实传了3个参数{state,increment,decrement}相当于以{...props}
* 的方式传递给Counter
*/
- index.js
import React from 'react'
import ReactDOM from 'react-dom'
import {createStore} from 'redux'
import {Provider} from 'react-redux'
import App from './containers/app'
import {counter} from './redux/reducers'
// 根据counter函数创建store对象
const store = createStore(counter)
// 定义渲染根组件标签的函数
ReactDOM.render(
(
// 用Provider来管理
<Provider store={store}>
<App/>
</Provider>
),
document.getElementById('root')
)
5.5 问题
- redux默认是不能进行异步处理的,
- 应用中又需要在redux中执行异步任务(ajax, 定时器)
6 redux异步编程
6.1 下载redux插件(异步中间件)
npm install --save redux-thunk
6.2 index.js
import {createStore, applyMiddleware} from 'redux'
import thunk from 'redux-thunk'
// 根据counter函数创建store对象
const store = createStore(
counter,
applyMiddleware(thunk) // 应用上异步中间件
)
6.3 redux/actions.js
// 异步action creator(返回一个函数)
export const incrementAsync = number => {
return dispatch => {
setTimeout(() => {
dispatch(increment(number))
}, 1000)
}
}
6.4 components/counter.jsx
incrementAsync = () => {
const number = this.refs.numSelect.value*1
this.props.incrementAsync(number)
}
6.5 containers/app.jsx
import {increment, decrement, incrementAsync} from '../redux/actions'
// 向外暴露连接App组件的包装组件
export default connect(
state => ({count: state}),
{increment, decrement, incrementAsync}
)(Counter)
7 纯函数和高阶函数
7.1 纯函数
- 一类特别的函数: 只要是同样的输入,必定得到同样的输出
- 必须遵守以下一些约束
a. 不得改写参数
b. 不能调用系统 I/O 的API
c. 能调用Date.now()或者Math.random()等不纯的方法 - reducer函数必须是一个纯函数
7.2 高阶函数
- 理解: 一类特别的函数
a. 情况1: 参数是函数
b. 情况2: 返回是函数 - 常见的高阶函数:
a. 定时器设置函数
b. 数组的map()/filter()/reduce()/find()/bind()
c. react-redux中的connect函数 - 作用:
a. 能实现更加动态, 更加可扩展的功能
如果对你有帮助,记得帮博主一键三连😊哦