Redux中间件(一):redux的使用

2021-01-06  本文已影响0人  Viewwei
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)))
  1. 安装redux
yarn add redux //安装redux
  1. 创建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
  1. 使用redux,使用redux,首先先导入store,通过store的getState函数获取state,通过订阅来更新组件,
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
上一篇 下一篇

猜你喜欢

热点阅读