image.png

简单概述

1、React是一个独立的库,redux也是一个独立的状态管理库,React中要更好的使用Redux,其实中间还少不了React-redux这个库,有点类型爱情的润滑剂【dulex】

2、useContext和useReducer是React hooks里面的俩个常用hooks,它本身就是属于React的API,所以理论上他和react搭配会更加丝滑。

3、在我们react中使用redux,我们要写很多的胶水代码,我们的reducer、actionType、mapperPropsToState、connect、这些API加大了新手的上手难度,项目庞大的话,目录结构会变的特别的恐怖,也增加了项目的学习曲线

Demo

1、首先我们使用useContext来创建最外层的Provide组建,和我们定义好的Context对象

  1. import React, { createContext, useReducer } from 'react'
  2. import reducer, { initState } from '../store/reducers'
  3. export const Context = createContext()
  4. export const Provide = (props) => {
  5. const [state, dispatch] = useReducer(reducer, initState)
  6. return (
  7. <Context.Provider value={{ dispatch, state }}>
  8. {props.children}
  9. </Context.Provider>
  10. )
  11. }

2、初始化我们的reducers,就是一个纯函数而已

  1. export const initState = { number: 0 }
  2. const reducers = (state = initState, action) => {
  3. switch(action.type) {
  4. case 'ADD': return {
  5. number: state.number + 1
  6. };
  7. case 'SUB': return {
  8. number: state.number - 1
  9. }
  10. default: return state;
  11. }
  12. }
  13. export default reducers;

3、渲染UI组件,UI组建中使用useContext获取dispatch和state

  1. import React, { useContext } from 'react'
  2. import { Context } from '../context/index'
  3. const MyText = () => {
  4. const { dispatch } = useContext(Context)
  5. return (
  6. <div>
  7. <button onClick={() => dispatch({ type: 'ADD' })}>+</button>
  8. <button onClick={() => dispatch({ type: 'SUB' })}>-</button>
  9. </div>
  10. )
  11. }
  12. export default MyText
  1. import React, { useContext } from 'react'
  2. import { Context } from '../context/index'
  3. const MyText = () => {
  4. const { state } = useContext(Context)
  5. return (
  6. <p>
  7. {state.number}
  8. </p>
  9. )
  10. }
  11. export default MyText

上面就是我们通过使用useReduce和useContext来模拟了我们的redux,但是他不能完全替代redux,毕竟redux最NB的还是他的中间价和生态。

可以使用useReduce和useContext封装一些涉及到深层次的数据共享组建、例如Page里面将request封装了等等。。。