Redux中间件(一):redux的使用
2021-01-06 本文已影响0人
Viewwei
- Redux Redux是基于Reducer来实现
- Reducer 来自数组(Array)中的reduce 例如数据相加
let array = [1,2,3,4]
let result = array.reduce((total,element)=>{
return total +=element
})
console.log(result); //10
数组中可以是基本数据,也可以是函数,函数实例如下
let f1 =(x) =>{console.log("f1L:"+x);return x}
let f2 =(x) =>{console.log("f2L:"+x);return x}
let f3 =(x) =>{console.log("f3L:"+x);return x}
let array = [f1,f2,f3]
let result = array.reduce((a,b) =>{
return (...args) =>{
a(b(...args))
}
})
result(1)
f3L:1
f2L:1
f1L:1
大约等于 f1(f2(f3(1)))
- Redux 使用如下
- 安装redux
yarn add redux //安装redux
- 创建reducer函数,并且创建store
import {createStore, applyMiddleware, combineReducers} from "redux";
function countReducer(state=0,action) {
switch(action.type){
case "ADD":
return state+=1
case "MINUS":
return state -=1
default:
return state
}
}
const store = createStore(countReducer)
export default store
- 使用redux,使用redux,首先先导入store,通过store的getState函数获取state,通过订阅来更新组件,
- 注意:订阅完成之后,在组件unmount之后需要取消订阅。实例代码如下
import React, { useCallback, useEffect, useState } from 'react';
import store from '../redux/index' //setp1 引入
let Redux = () =>{
const[count,setCount] = useState(store.getState()) //store.getState() 获取state的值
useEffect(()=>{
let sub = store.subscribe(() =>{
//订阅更新
setCount(store.getState())
})
return ()=>{
//组件unmount之后需要取消订阅
sub.unsubscribe()
}
},[])
const add = () =>{
store.dispatch({type:"ADD"})
}
const minix =() =>{
store.dispatch({type:"MINUS"})
}
const delayed = ()=>{
store.dispatch((dispath,getState)=>{
setTimeout(() => {
dispath({type:"ADD"})
}, 1000);
})
}
return <div>
<h3>ReduxPage</h3>
<p>{count}</p>
<button onClick={e=>add()}>增加</button>
<button onClick={e=>minix()}>减少</button>
<button onClick={e=>delayed()}>延时增加</button>
</div>
}
export default Redux
成功实例:点击添加可以正常使用
image.png