React Hooks之useReducer

useReducer :接受类型为 (state, action) => newState 的reducer,并返回与 dispatch 方法配对的当前状态。(如果你熟悉Redux,你已经知道它是如何工作的。)

下面定义两个计数器Counter组件CounterTest组件,使用 useReducer 使它们共享一个count state,当一个组件的 count state发生变化时,另一个组件的count state也会相应的改变。

  1. reducer.js
import { useReducer } from "react";

const initialState = 0;

function reducer(state, action) {
  switch (action.type) {
    case "reset":
      return initialState;
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    default:
      // A reducer must always return a valid state.
      // Alternatively you can throw an error if an invalid action is dispatched.
      return state;
  }
}

export default reducer;

  1. Counter.js
import React from "react";

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

export default Counter;

  1. CounterTest.js
import React from "react";

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

export default CounterTest;

  1. index.js
import React, { useReducer } from "react";
import reducer from "./reducer";
import Counter from "./Counter";
import CounterTest from "./CounterTest";

const App = () => {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <div className="App">
      <Counter state={state} dispatch={dispatch} />
      <CounterTest state={state} dispatch={dispatch} />
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

ps:此处还有两种方法对代码进行优化:
方法一:将共同的状态 state 和 dispatch 通过 React.createContext存入到context中,再通过useContext API获取context中的内容。
方法二:直接采用React Context API
接下来会对这两种方法分别进行说明。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值