1.基本使用
import React,{useReducer}from 'react'
// eslint-disable-next-line import/no-anonymous-default-export
export default ()=>{
//创建一个reducer
const [count,dispatch]=useReducer((state,action)=>{
switch (action) {
case 'add':
return state+1;
case 'sub':
return state>0?state-1:0
default:
return state
}
},0)
return(
<>
<h1> 这个值是:{count}</h1>
<button onClick={()=>dispatch('add')}>点击加一</button>
<button onClick={()=>dispatch('sub')}>点击减一</button>
</>
)
}
2.案例
//修改颜色/Color.jsx
import React,{createContext,useReducer}from 'react'
export const ChangeColor=createContext({})
export const UPDATECOLOR='UPDATECOLOR'
const reducer=(state,action)=>{
switch (action.type) {
case UPDATECOLOR:
return action.color
default:
return state
}
}
// eslint-disable-next-line import/no-anonymous-default-export
export const Colors= (props)=>{
const [color,dispatch]=useReducer(reducer,'blue')
return(
<>
<ChangeColor.Provider value={{color,dispatch}}>
{ props.children}
</ChangeColor.Provider>
</>
)
}
//content.jsx
import React from 'react'
import Buttons from './Buttons'
import Txt from './Txt'
import { Colors } from './Colors'
// eslint-disable-next-line import/no-anonymous-default-export
export default ()=>{
return(
<>
{/* 需要使用color组件将其他俩个组件包裹,共享数据 */}
<Colors>
<Txt />
<Buttons />
</Colors>
</>
)
}
//Txt.jsx
import React,{useContext}from 'react'
import { ChangeColor } from './Colors'
// eslint-disable-next-line import/no-anonymous-default-export
export default ()=>{
let {color}=useContext(ChangeColor)
return(
<>
<h1 style={{color:color}}>这行文字的颜色是:{color}</h1>
</>
)
}
Buttons.jsx
//将dispatch分发出去,在外部传入action
import React,{useContext} from 'react'
import {ChangeColor,UPDATECOLOR} from "./Colors"
// eslint-disable-next-line import/no-anonymous-default-export
export default ()=>{
const {dispatch}=useContext(ChangeColor)
return(
<>
<button style={{background:'#00ffff',color:'#fff'}} onClick={()=>dispatch({type:UPDATECOLOR,color:'red'})}>修改颜色是红色</button>
<button style={{background:'#00ff00',color:'#fff'}} onClick={()=>dispatch({type:UPDATECOLOR,color:'yellow'})}>修改颜色是黄色</button>
</>
)
}