【发布时间】: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