通常reducer是和redux一起使用的,因此很多人看了useReducer的第一反应应该就是redux的某个替代品,其实并不是的。
useReducer只是useState的一种替代品,并不能替代redux
useState写法
import React, { useState } from 'react'
const Hook = () => {
const [num, setNum] = useState(0)
return (
<>
<p>数字{num}</p>
<button type="button" onClick={(e) => setNum(num + 1)}>
点击+1
</button>
<button type="button" onClick={(e) => setNum(num - 1)}>
点击-1
</button>
</>
)
}
export default Hook
useReducer写法
function reducer(state: any, action: any) {
switch (action.type) {
case 'add':
return { ...state, num: state.num + 1 }
break
case 'reduce':
return { ...state, num: state.num - 1 }
}
return state
}
import React, { useReducer } from 'react'
const Hook = () => {
const [state, dispatch] = useReducer(reducer, { num: 0 })
return (
<>
<p>数字{state.num}</p>
<button type="button" onClick={(e) => dispatch({ type: 'add' })}>
点击+1
</button>
<button type="button" onClick={(e) => dispatch({ type: 'reduce' })}>
点击-1
</button>
</>
)
}
export default Hook
多个地方引入使用reducer函数,没有共享state,只是函数处理共享了,并没有共享数据 效果如下:
数据并没有互相影响,都是独立的
结束语
希望大家能够喜欢我的文章,我真的很用心在写,也希望通过文章认识更多志同道合的朋友。
最后伙伴们,如果喜欢我的可以给点一个小小的赞👍或者关注➕都是对我最大的支持。