reducer是一个函数(state, action) => newState:接收当前应用的state和触发的动作action,计算并返回最新的state
useReducer第一个参数:reducer函数,。第二个参数:初始化的state。返回值为最新的state和dispatch函数(用来触发reducer函数,计算对应的state)
import React, { createContext,useReducer } from 'react'
export const ColorContext = createContext({})
export const UPDATE_COLOR = "UPDATE_COLOR"
const reducer = (state,action)=>{
switch(action.type){
case UPDATE_COLOR:
return action.color
default:
return state
}
}
export const Color = props=>{
console.log(props)
const [color,dispatch] = useReducer(reducer,'blue')
return(
<ColorContext.Provider value={{color,dispatch}}>
{props.children}
</ColorContext.Provider>
)
}
引入Color 包裹子组件
import React from 'react'
import ShowArea from './showArea'
import Buttons from './Buttons'
import {Color} from './color'
function Example6(){
return (
<div>
<Color>
<ShowArea/>
<Buttons/>
</Color>
</div>
)
}
export default Example6
用useContex接受共享的dispatch并通过dispatch修改
import React,{useContext} from 'react'
import {ColorContext,UPDATE_COLOR} from './color'
function Buttons(){
const {dispatch} = useContext(ColorContext)
return(
<div>
<button onClick={()=>dispatch({type:UPDATE_COLOR,color:"red"})}>红色</button>
<button onClick={()=>dispatch({type:UPDATE_COLOR,color:"yellow"})}>黄色</button>
</div>
)
}
export default Buttons
展示拿到的共享值
import React, {useContext} from 'react';
import {ColorContext} from './color'
function ShowArea(){
const {color} = useContext(ColorContext)
return(<div style={{color}}>字体颜色为{color}</div>)
}
export default ShowArea;