【问题标题】:How to pass argument set of useReducer() hook?如何传递 useReducer() 钩子的参数集?
【发布时间】:2022-07-14 00:14:38
【问题描述】:

我正在学习反应,我正在尝试使用 useReducer() 并使其根据某种状态执行两项任务。我的App.js 如下所示。当我单击按钮时,值不会传递给setCounterValue。这里有什么问题?

import "./styles.css";

import { useReducer } from "react";

export default function App() {
  const [counterValue, setCounterValue] = useReducer(
    (a) => (a[1] ? [a[0] + 1, a[1]] : [a[0] - 2, a[1]]), //
    [1, false] // counter and a flag to inc/dec
  );
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>
        Start editing to see [{counterValue[0]}, {counterValue[1].toString()}]
        magic happen!!
      </h2>
      <button onClick={() => setCounterValue([1, true])}>Inc</button>
      <button onClick={() => setCounterValue()}>Dec</button>
    </div>
  );
}

【问题讨论】:

  • 您缺少useReducer 回调的第二个参数:action

标签: reactjs


【解决方案1】:

你可以使用它完美地工作!

const initialState = {count: 0};

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, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-24
    • 2021-06-29
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    相关资源
    最近更新 更多