React--hooks-- useReducer数据状态管理

前言:

之前我们在写react组件时,我们要么是通过类组件内定义state来管理数据,要么就是在函数组件内使用useState来管理数据。但如果一个数据牵扯到了很多个组件,那么我们管理起来就会十分麻烦。
所以 react-hooks 为我们提供了一个类似与redux的功能 – useReducer来帮助我们集中式的处理复杂的state管理。


一、useReducer的使用

useReducer接收三个参数(第三个可不传):

第一个参数:reducer函数。

第二个参数:初始化的state。返回值为最新的state和dispatch函数(用来触发reducer函数,计算对应的state)。按照官方的说法:对于复杂的state操作逻辑,嵌套的state的对象,推荐使用useReducer。

第三个参数(一个函数,用于惰性初始化):你可以选择惰性地创建初始 state。为此,需要将 init 函数(接收initialState,可对其进行一些处理)作为 useReducer 的第三个参数传入,这样初始 state 将被设置为 initialArg。

const [state, dispatch] = useReducer(reducer, initialState, init);

用useReducer实现一个计数器:

const initialState = {
   count: 0}; // 设置初始状态

// reducer:负责生成新的State
function reducer(state, action) {
    // 定义 reducer 函数,在这里面对状态改变 进行统一处理,
// state:是上一次state的状态数据
// action:是基于dispatch派发的行为数据:值 或 一个对象
  switch (action.type) {
   
  // 根据action 对 State 进行修改
    case 'increment':
      return {
   count: state.count + 1};
    case 'decrement':
      return {
   count: state.count - 1};
    default:
      throw new Error();
  }
}
function Counter() {
   
  const [state, dispatch] = useReducer(reducer, initialState);
  // dispatch 派发action
  return (
    <>
      Count: {
   state.count}
      <button onClick={
   () => dispatch({
   type: 'decrement'})}>-</button>
      <button onClick={
   () => dispatch({
   type: 'increment'})}>+</button>
    </>
  );
}

使用useState实现计数器:

function App() {
   
    const [state, setState] = useState({
   
        count: 0
    });
    const increment 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值