增减计数器小案例
新建Example5.js文件:
import React, { useReducer } from 'react';
function ReducerDemo(){
const [count,dispatch] = useReducer((state,action)=>{
switch(action){
case 'add':return state + 1;
case 'delete':return state - 1;
default:return state;
}
},0) //0是初始值
return (
<div>
<h2>现在的分数是{count}</h2>
<button onClick={()=>{dispatch('add')}}>Increment</button>
<button onClick={()=>{dispatch('delete')}}>Decrement</button>
</div>
)
}
export default ReducerDemo;
实现效果:
文字变色小案例
要实现的效果如下:
useReducer和useContext合并使用可以实现类似Redux的效果。
useContext实现状态共享,useReducer实现业务控制(相当于Redux中的Reducer)。
在src下新建文件夹example6用来存放这个小案例的相关文件。
状态共享
首先创建显示字的部分ShowArea.js:
import React from 'react';
function ShowArea(){
return (
<div style={{color:'blue'}}>字体颜色为blue</div>
)
}
export default ShowArea;
新建按钮部分Buttons.js:
import React from 'react';
function Buttons(){
return(
<div>
<button>红色</button>
<button>黄色</button>
</div>
)
}
export default Buttons;
新建Example6组合以上两个组件:
import React from 'react';
import Buttons from './Buttons';
import ShowArea from './ShowArea';
function Example6(){
return (
<div>
<ShowArea/>
<Buttons/>
</div>
)
}
export default Example6;
新建color.js,共享color:
import React, { createContext } from 'react';
export const ColorContext = createContext({});
export const Color = props=>{
return(
<ColorContext.Provider value={{color:"yellow"}}>
{props.children}
</ColorContext.Provider>
)
}
修改Example6.js,用Color包裹要传递值的组件:
import React from 'react';
import Buttons from './Buttons';
import { Color } from './color';
import ShowArea from './ShowArea';
function Example6(){
return (
<div>
<Color>
<ShowArea/>
<Buttons/>
</Color>
</div>
)
}
export default Example6;
修改ShowArea.js,接收共享值color:
import React , {useContext} from 'react';
import {ColorContext} from './color';
function ShowArea(){
const {color} = useContext(ColorContext);
return (
<div style={{color:color}}>字体颜色为blue</div>
)
}
export default ShowArea;
运行可以看到字体颜色已经变成了黄色。
业务逻辑编写
在color.js中编写reducer方法进行业务处理:
import React, { createContext , useReducer} from 'react';
export const ColorContext = createContext({});
//useReducer编写业务逻辑
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=>{
const [color,dispatch] = useReducer(reducer,'blue');//初始值为blue
return(
<ColorContext.Provider value={{color,dispatch}}>
{props.children}
</ColorContext.Provider>
)
}
修改Buttons.js,通过dispatch传递action,完成点击事件:
import React , {useContext} from 'react';
import { ColorContext, UPDATE_COLOR } from './color';
function Buttons(){
const {dispatch} = useContext(ColorContext);//得到dispatch
return(
<div>
<button onClick={()=>{dispatch({type:UPDATE_COLOR,color:'red'})}}>红色</button>
<button onClick={()=>{dispatch({type:UPDATE_COLOR,color:'yellow'})}}>黄色</button>
</div>
)
}
export default Buttons;
可以成功实现点击按钮切换字体颜色。