likes
comments
collection
share

Day 42/100 React Hook之useReducer基本用法

作者站长头像
站长
· 阅读数 28

(一)需求

最近在学习React,学到了React Hook 做了 useReducer Demo。

(二)介绍

使用useReducer是为了方便状态管理,用法和Redux特别像。

/*
 * @Author: ArdenZhao
 * @Date: 2022-04-18 17:26:35
 * @LastEditTime: 2022-04-18 18:09:53
 * @FilePath: /react-ts/src/components/react/10-Hook-useReducer.js
 * @Description: file information
 */
import { useReducer } from 'react';
import { Button } from 'antd';
import "antd/dist/antd.css";

// 改变的方法
const reducer = (state, action) => {
  switch (action.type) {
    case 'add':
      // console.log('[ state ] >', state, { ...state })
      return { ...state, count: state.count + 1 };
    case 'minus':
      return { ...state, count: state.count - 1 };
    default:
      return state;
  }
}

// 定义对象
let initialState = { count: 10, name: "reducer" }

//初始化方法
const init = initialState => {
  return { name: "reducer", count: initialState.count + 2 }; // 初始化
}

function HookUseReducer(props) {
  // useReducer
  const [state, dispatch] = useReducer(reducer, initialState, init);

  return (
    <div>
      <h1>Learn, {props.name}</h1>
      <p>计数器:{state.count}-{state.name}</p>
      <Button onClick={() => dispatch({ type: 'add' })}>加+</Button>
      <Button onClick={() => dispatch({ type: 'minus' })}>减-</Button>
    </div>
  );
}
export default HookUseReducer

写在最后的话

学习路上,常常会懈怠。

《有想学技术需要监督的同学嘛~》https://mp.weixin.qq.com/s/Fy...

如果有需要的伙伴,可以加我微信:learningisconnecting或者可以关注我的公众号:国星聊成长(我会分享成长的方法)
转载自:https://segmentfault.com/a/1190000041723515
评论
请登录