近两年前端技术的发展如火如荼,大量的前端项目都在使用或转向 Vue 和 React 的阵营, 由前端渲染页面的单页应用占比也愈来愈高,这就表明前端工做的复杂度也在直线上升,前端页面上展现的信息愈来愈多也愈来愈复杂。咱们知道,任何状态都须要进行管理,那么今天咱们来聊聊前端状态管理。
前端状态管理第三方出名的库有: Flux、Redux、Vuex、Mobx 等
这里专讲react的状态管理演变javascript
开发者门接触最多的应该就是redux,这里从浅入深的来逐步学习吧前端
1 .单纯的使用纯redux库,参考redux1java
// Action export const commonType = {//action type SET_AGE: 'SET_AGE' } export function setAge(payload: any) {//action creator return { type: commonType.SET_AGE, payload } } // reducer const commonReducer = (state = initialState, action: any) =>{ switch (action.type) { case commonType.SET_AGE: return { ...state, ...action.payload }; default: return state; } } // store import { createStore } from 'redux' let store = createStore(allReducer);
// 使用(订阅) import store from '../redux/store' export default class App extends React.Component<any, any> { constructor(props: any) { super(props); this.state = {iptVal:0}; } componentDidMount() { store.subscribe(() =>{ let {common:{age:iptVal}}= store.getState(); this.setState({iptVal}); }) } render() { return (<div>{this.state.iptVal}</div>); } }
// 使用(广播) import store from '../redux/store' export default class A extends React.Component<any, any> { constructor(props: any) { super(props); this.state = {iptVal:0}; } componentDidMount() { store.subscribe(() =>{ let {common:{age:iptVal}}= store.getState(); this.setState({iptVal}); }) } iptChange = (e: any) =>{ store.dispatch(actions.setAge({ age:e.target.value })); } render() { const { iptVal } = this.state; return ( <> <input type="text" value={iptVal} onChange={this.iptChange} /> <div>{iptVal}</div> </> ) } }
缺点很明显,须要在改变和监听数据的地方都引入store,并手动与组件关联,所以有了第2种方式react
2 .使用redux + react-redux方式, 参考redux2redux
// Action export const commonType = {//action type SET_AGE: 'SET_AGE' } export function setAge(payload: any) {//action creator return { type: commonType.SET_AGE, payload } } // reducer import { combineReducers } from 'redux'; const commonReducer = (state = initialState, action: any) =>{ switch (action.type) { case commonType.SET_AGE: return { ...state, ...action.payload }; default: return state; } } const allReducer = combineReducers({ common:commonReducer }) // store import { createStore } from 'redux' let store = createStore(allReducer);
// 使用(订阅) import { connect } from 'react-redux' class App extends React.Component<any, any> { constructor(props: any) { super(props); } render() { return (<div>{this.props.iptVal}</div>); } } export default connect( (state: any) => { return {iptVal: state.common.age} },null )(App);
// 使用(广播) import { connect } from 'react-redux' class A extends React.Component<any, any> { constructor(props: any) { super(props); } render() { return ( <> <input type="text" value={this.props.iptVal} onChange={this.props.iptChange} /> <div>{this.props.iptVal}</div> </> ) } } export default connect( (state: any) => { return {iptVal: state.common.age} }, (dispatch: any)=>{return { iptChange(e: any){ dispatch(actions.setAge({ age:e.target.value })) } }} )(A);
这样就不用手动处理全局状态与react的关系了,若是你了解注解(装饰器),看起来代码就更简单了,反正我是没有配置成功,你能够试试
不过action creator和reducer建立起来好费劲。action creator要写大量的重复代码,reducer遍地的switch case,因此便有了第3种方式。异步
3 .redux + react-redux + redux-actions, 源代码在redux3ide
// Action import { createAction } from 'redux-actions'; export const commonType = {SET_AGE: 'SET_AGE'};//action type export const setAge = createAction(commonType.SET_AGE);//action creator // reducer import { combineReducers } from 'redux'; import { handleActions } from "redux-actions"; const initialState = {age: 0}; //初始化state let reducers = { [commonType.SET_AGE](state: any, action: any){ let { payload } = action; return {...state,...payload}; } }; const commonReducer = handleActions<any>(reducers,initialState); const allReducer = combineReducers({ common:commonReducer }) // store import { createStore } from 'redux' let store = createStore(allReducer);
// 使用(订阅) import { connect } from 'react-redux' class App extends React.Component<any, any> { constructor(props: any) { super(props); } render() { return (<div>{this.props.iptVal}</div>); } } export default connect( (state: any) => { return {iptVal: state.common.age} },null )(App);
// 使用(广播) import { connect } from 'react-redux' class A extends React.Component<any, any> { constructor(props: any) { super(props); } render() { let {iptVal,iptChange} = this.props; return (<> <input type="text" value={iptVal} onChange={iptChange}/> <div>{iptVal}</div> </>) } } export default connect( (state: any) => { return {iptVal: state.common.age} }, (dispatch: any)=>{return { iptChange(e: any){ dispatch(actions.setAge({ age:e.target.value })) } }} )(A);
这样作效果已经很好了,至少在hooks来以前,这是你们广泛使用的方法来管理react的全局状态。可是hooks以后,我推荐以下,缘由是 不用引入任何第三方包函数
使用做用域之React.Context,这个学过java的人都知道,此对象是贯穿整个应用的。经过注入便监听 Context来达到redux一样的效果,好不用引入第三方包。参考context学习
// Context const commonContext = React.createContext({ //初始化,不具体实现 age: 0, setAge: (age: number) => {} }); // 使用(注入须要订阅的组件) import {useState} from 'react'; import CommonContext from './context'; export default const App = () => { const [ age, setAges ] = useState(10); let myValue = { age,setAge(age: number){setAges(age)} }; return (<> <CommonContext.Provider value={myValue}> <A/> <B/> <C/> <div>{age}</div> </CommonContext.Provider> </>); }
// 使用(发起广播) import * as React from 'react'; import { useContext } from 'react'; import commonContext from '../context'; export default const B =()=> { const commonCtx = useContext(commonContext); const onChange = (e: any)=>{ commonCtx.setAge(e.target.value) }; return (<> <div>{commonCtx.age}</div> <input type="text" onChange={onChange} value={commonCtx.age}/> </>) }
// 使用(订阅监听)--函数式组件使用hooks订阅 import * as React from 'react'; import { useContext } from 'react'; import commonContext from '../context'; export default const A = (props: any) => { const commonCtx = useContext(commonContext); return (<div>{commonCtx.age}</div>) }
// 使用(订阅监听)--类组件两种方式订阅 import * as React from 'react' import commonContext from '../context'; export default class C extends React.Component <any,any> { static contextType = commonContext; constructor(props: any){ super(props); } render(){ return ( // 在没有useContext的hooks以前,一般这样取得和监听Context <> 方式1:this.context,使用Class.contextType你能够在任何生命周期中访问到this.context: <div>{this.context.age}</div> 方式2:Consumer, 让你在函数式组件中完成订阅 context: <commonContext.Consumer> {commonCtx=><div>{commonCtx.age}</div>} </commonContext.Consumer> </> ) } };
若是只是用Context,功能能实现,可是还不是很灵活,好比动态的value(state和reducer)你得本身手动建立并关联,因此便有了以下办法。this
这是目前react官方最推荐的使用方式,也是本文一路想引伸的,若是想单独看useReducer的使用方式请看useReducer,最终结合版看useReducerContext
// Context const commonContext: any = React.createContext(null); //action export const commonType = { SET_AGE:'SET_AGE' } export const setAge = (payload: any) =>{ return { type: commonType.SET_AGE, payload } } //reducer const initialState: any = {age: 0}; function reducer(state: any, action: any) { switch (action.type) { case commonType.SET_AGE: let { payload } = action; return {...state,...payload}; default: throw new Error(); } } export { initialState, reducer };
//使用(注入须要订阅的组件) import * as React from 'react'; import A from './components/a'; import B from './components/b'; import C from './components/c'; import {useReducer} from 'react'; import { reducer, initialState } from './redux/reducer/common'; import CommonContext from './context'; export default () => { const myValue = useReducer(reducer, initialState); return ( <div> <CommonContext.Provider value={myValue}> <A/> <B/> <C/> <div>{myValue[0].age}</div> </CommonContext.Provider> </div> ); }
// 使用(发起广播) import * as React from 'react'; import { useContext } from 'react'; import commonContext from '../context'; export default const B =()=> { const [state,dispatch] = useContext(commonContext); const onChange = (e: any)=>{ let payload = { age: e.target.value } dispatch(setAge(payload)) }; return (<> <div>{state.age}</div> <input type="text" onChange={onChange} value={state.age}/> </>) }
// 使用(订阅监听)--函数式组件使用hooks订阅 import * as React from 'react'; import { useContext } from 'react'; import commonContext from '../context'; export default const A = (props: any) => { const [state] = useContext(commonContext); return (<div>{state.age}</div>) }
// 使用(订阅监听)--类组件两种方式订阅 import * as React from 'react' import commonContext from '../context'; export default class C extends React.Component <any,any> { static contextType = commonContext; constructor(props: any){ super(props); } render(){ return ( // 在没有useContext的hooks以前,一般这样取得和监听Context <> {/* 方式1:this.context,使用Class.contextType你能够在任何生命周期中访问到this.context */} <div>{this.context[0].age}</div> {/* 方式2:Consumer, 让你在函数式组件中完成订阅 context */} <commonContext.Consumer> {([state]:any)=>{ return <div>{state.age}</div> }} </commonContext.Consumer> </> //总结:使用useContext()时候咱们能够不须要使用Consumer了,看你喜欢哪一个了 ) } };
这只是状态管理最基本的用法,还有特殊状况 好比异步action等等,没有专门讲,感兴趣的能够去看看,不过建议先看最普通和基础的