react: useReducer

相比useState, 用来处理更为复杂的修改数据方式

// 使用示例
import  { useReducer } from "react";
const reducer函数 = (state, action) => {
 根据action做判断 去返回结果
 return state
}
const [state, dispatch函数] = useReducer(reducer函数, action)

使用
dispatch(传递不同的action)

在https://ant.design/components/button-cn 打开一个codesanbox替换下面代码保存即可

import React, { useReducer } from "react";

// 定义 reducer。它接收当前状态和一个代表“动作”的对象,返回新状态。
function reducer(state, action) {
  switch (action.type) {
    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, { count: 0 });

  return (
    <div>
      Count: {state.count}
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
    </div>
  );
}

export default Counter;

你可能感兴趣的:(react18,react.js,javascript,前端)