1.redux中间件
中间件提供第三方插件的模式,自定义拦截 action -> reducer 的过程。变为 action -> middlewares -> reducer。这种机制可以让我们改变数据流,实现如异步action ,action 过滤,日志输出,异常报告等功能
redux-logger:提供日志输出,每次action修改state时,都会在控制台打印出关键信息,便于开发者追溯状态。
// src/store/index.tsx
import {createStore,applyMiddleware} from 'redux'
import logger from 'redux-logger'
import thunk from 'redux-thunk'
const reducer = function(state:any,actions:any){
if(!state){
return {
count:10,
msg:'hello redux'
}
}
switch(actions.type){
case "PLUS":
return {
...state,
count:state.count+1
}
break;
default:
return state
break
}
}
const store =applyMiddleware(logger,thunk)(createStore)(reducer)
export default store
// 异步action,就是指action的值为函数,异步action中一般都会调用同步action,异步action不是必须要用的。
redux-thunk:处理异步操作
// src/store/index.tsx
import React, { useEffect, useState } from 'react';
import yayJpg from '../assets/yay.jpg';
import store from '../store/index'
export default function HomePage() {
const [user,setuser] = useState(store.getState().count)
useEffect(()=>{
store.subscribe(()=>{
setuser(store.getState().count)
})
},[])
// const upd = ()=>{
// store.dispatch({type:"PLUS"})
// }
const openFormAsync = () => {
// 返回一个函数,参数是dispatch函数,函数里面包含异步操作,且一般要调用同步action
store.dispatch((dispatch:any,getState:any)=>{
setTimeout(() => {
console.log(getState())
dispatch({type:'PLUS'})
},2000)
})
}
return (
<div>
<h2>{user}</h2>
<p>
<img src={yayJpg} width="388" />
</p>
<p>
To get started, edit <code>pages/index.tsx</code> and save to reload.
<button onClick={openFormAsync}>修改</button>
</p>
</div>
);
}
redux-promise:处理异步操作,actionCreator的返回值是promise
2.React高阶组件
高阶函数(Higher-order function),至少满足下列一个条件的函数
接受一个或多个函数作为输入,输出一个函数
在React中,高阶组件即接受一个或多个组件作为参数并且返回一个组件,本质也就是一个函数,并不是一个组件
高阶组件的主要功能是封装并分离组件的通用逻辑,让通用逻辑在组件间更好地被复用
高阶组件可以传递所有的props,但是不能传递ref
高阶组件能够提高代码的复用性和灵活性,在实际应用中,常常用于与核心业务无关但又在多个模块使用的功能,如权限控制、日志记录、数据校验、异常处理、统计上报等
import React from 'react'
const Gaojie = (Son: any) => {
return function () {
const arr = {
one: '马新明',
two: '小黑'
}
return <Son {...arr} />
}
}
const Gao = (props: any) => {
// console.log(props,'props');
return (
<div>
{props.one}
</div>
)
}
const L=(props:any)=>{
return(
<div>
{props.two}
</div>
)
}
const Fourther=()=>{
return(
<>
<One/>
<T/>
</>
)
}
const One = Gaojie(Gao)
const T = Gaojie(L)
export default Fourther