1.基本使用

  1. import React,{useReducer}from 'react'
  2. // eslint-disable-next-line import/no-anonymous-default-export
  3. export default ()=>{
  4. //创建一个reducer
  5. const [count,dispatch]=useReducer((state,action)=>{
  6. switch (action) {
  7. case 'add':
  8. return state+1;
  9. case 'sub':
  10. return state>0?state-1:0
  11. default:
  12. return state
  13. }
  14. },0)
  15. return(
  16. <>
  17. <h1> 这个值是:{count}</h1>
  18. <button onClick={()=>dispatch('add')}>点击加一</button>
  19. <button onClick={()=>dispatch('sub')}>点击减一</button>
  20. </>
  21. )
  22. }

2.案例

  1. //修改颜色/Color.jsx
  2. import React,{createContext,useReducer}from 'react'
  3. export const ChangeColor=createContext({})
  4. export const UPDATECOLOR='UPDATECOLOR'
  5. const reducer=(state,action)=>{
  6. switch (action.type) {
  7. case UPDATECOLOR:
  8. return action.color
  9. default:
  10. return state
  11. }
  12. }
  13. // eslint-disable-next-line import/no-anonymous-default-export
  14. export const Colors= (props)=>{
  15. const [color,dispatch]=useReducer(reducer,'blue')
  16. return(
  17. <>
  18. <ChangeColor.Provider value={{color,dispatch}}>
  19. { props.children}
  20. </ChangeColor.Provider>
  21. </>
  22. )
  23. }
  1. //content.jsx
  2. import React from 'react'
  3. import Buttons from './Buttons'
  4. import Txt from './Txt'
  5. import { Colors } from './Colors'
  6. // eslint-disable-next-line import/no-anonymous-default-export
  7. export default ()=>{
  8. return(
  9. <>
  10. {/* 需要使用color组件将其他俩个组件包裹,共享数据 */}
  11. <Colors>
  12. <Txt />
  13. <Buttons />
  14. </Colors>
  15. </>
  16. )
  17. }
  1. //Txt.jsx
  2. import React,{useContext}from 'react'
  3. import { ChangeColor } from './Colors'
  4. // eslint-disable-next-line import/no-anonymous-default-export
  5. export default ()=>{
  6. let {color}=useContext(ChangeColor)
  7. return(
  8. <>
  9. <h1 style={{color:color}}>这行文字的颜色是:{color}</h1>
  10. </>
  11. )
  12. }
  1. Buttons.jsx
  2. //将dispatch分发出去,在外部传入action
  3. import React,{useContext} from 'react'
  4. import {ChangeColor,UPDATECOLOR} from "./Colors"
  5. // eslint-disable-next-line import/no-anonymous-default-export
  6. export default ()=>{
  7. const {dispatch}=useContext(ChangeColor)
  8. return(
  9. <>
  10. <button style={{background:'#00ffff',color:'#fff'}} onClick={()=>dispatch({type:UPDATECOLOR,color:'red'})}>修改颜色是红色</button>
  11. <button style={{background:'#00ff00',color:'#fff'}} onClick={()=>dispatch({type:UPDATECOLOR,color:'yellow'})}>修改颜色是黄色</button>
  12. </>
  13. )
  14. }