Redux
简介
其实就是一个集中的状态管理技术, 类似于VueX, 以及后端的分布式配置中心, 在前端的文章里提后端,是不是不太好~, 但是能学习这个技术的人, 从简短的一句话中应该就已经简单的了解了这个技术,以及它的使用情况, 我就不过多写概念了, 主要写使用方式
Redux工作流程
三个核心概念
Action
- 动作对象
- 包含两个属性
字段 |
作用 |
数据类型 |
是否唯一 |
是否必填 |
type |
标识属性 |
字符串 |
是 |
是 |
data |
数据属性 |
任意 |
否 |
否 |
{
"type":"add",
"data:":{
"name":"flower",
"age":18
}
}
Reducer
- 用于初始化状态, 加工状态
- 加工时, 依据旧的state和action,产生新的state的纯函数
Store
- 将state, action, reducer 联系在一起的对象
- 如何获取:
import {createStore} from 'redux'
import reducer from './reducers'
const store = createStore(reducer)
- 此对象的功能
函数 |
参数 |
作用 |
getState() |
无 |
获取state |
dispatch(action) |
action对象 |
分发action,处罚reducer调用,产生新的state |
subscribe(listener) |
listener对象 |
注册监听,当产生新的state时,自动调用 |
添加依赖
yarn add redux
求和案例
React版本
import React, {Component} from 'react';
class Count extends Component {
state = {
count: 0
}
render() {
return (
<div style={
{textAlign: 'center'}}>
<h1>当前求和为:{
this.state.count}</h1>
<select ref={c => this.count = c} style={
{width: '50px'}}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button style={
{marginLeft: '10px'}} onClick={
this.sum('add')}>+</button>
<button style={
{marginLeft: '10px'}} onClick={
this.sum('re')}>-</button>
<button style={
{marginLeft: '10px'}} onClick={
this.sum('j')}>当前求和为奇数+</button>
<button style={
{marginLeft: '10px'}} onClick={
this.sum('async')}>异步+</button>
</div>
);
}
sum = type => {
return event => {
let {value} = this.count
value = parseInt(value)
let {count} = this.state
if (type === 'add') {
count = count + value
this.setState({count})
return
}
if (type === 're') {
count = count - value
this.setState({count})
return
}
if (type === 'j') {
if (count % 2 !== 0) {
count = count + value
this.setState({count})
}
return;
}
if (type === 'async') {
count = count + value
setTimeout(() => {
this.setState({count})
}, 2000)
}
}
}
}
export default Count;
Redux精简版
创建store.js
/**
* 1: 引入createStore
* 2: 引入为自定义组件服务的reducer
* 3: 对外暴露store
*/
import {legacy_createStore as createStore} from 'redux'
import countReducer from './count_reducer'
export default createStore(countReducer)
创建count_reducer.js
/**
* 1: 该文件是用于创建一个为Count组件服务的reducer, reducer的本质就是一个函数
* 2: reducer函数会接收到两个参数, 分别为: 之前的状态(preState), 动作对象(action)
*/
const initValue = 0
export default function countReducer(preState = initValue, action) {
const {type, data} = action
if (type === 'add')
return preState + data
if (type === 're')
return preState - data
return preState
}
使用redux改造原有Count组件
import React, {Component} from 'react';
import store from "../../redux/count/store";
class Count extends Component {
componentDidMount() {
// 检测Redux中状态的变化, 只要变化, 就调用Render
store.subscribe(()=>{
// 调用刷新页面函数, 啥也不干就 重新渲染一下render
this.forceUpdate()
})
}
render() {
return (
<div style={
{textAlign: 'center'}}>
<h1>当前求和为:{store.getState()}</h1>
<select re