javascript - 对分配给 onClick 事件的 useReducer 的用法感到困惑
问题描述
我正在阅读此博客以更好地理解 React 的关键道具,作者使用的一个示例是
function Counter() {
console.log('Counter called')
const [count, setCount] = React.useState(() => {
console.log('Counter useState initializer')
return 0
})
const increment = () => setCount(c => c + 1)
React.useEffect(() => {
console.log('Counter useEffect callback')
return () => {
console.log('Counter useEffect cleanup')
}
}, [])
console.log('Counter returning react elements')
return <button onClick={increment}>{count}</button>
}
function CounterParent() {
// using useReducer this way basically ensures that any time you call
// setCounterKey, the `counterKey` is set to a new object which will
// make the `key` different resulting in React unmounting the previous
// component and mounting a new one.
const [counterKey, setCounterKey] = React.useReducer(c => c + 1, 0)
return (
<div>
<button onClick={setCounterKey}>reset</button>
<Counter key={counterKey} />
</div>
)
}
我想我理解他使用reset
按钮使key
道具与众不同的部分。但是useReducer
对我来说看起来很陌生。首先useReducer
应该返回 a dispatch
,在这种情况下我猜它是setCounterKey
,然后它被传递给onClick
prop。但我仍然不明白为什么这甚至有效。我们应该调用具有我们想要的动作类型和有效负载的对象吗?
我想知道他为什么不使用useState
。我试图将代码修改为
const [counterKey, setCounterKey] = React.useState(0);
但我收到了这个错误
警告:出于性能原因,此合成事件被重用。如果您看到此内容,则表示您正在访问已
movementY
发布/无效合成事件的方法。这是一个无操作功能。如果您必须保留原始合成事件,请使用 event.persist()。
谁能给我解释一下?
解决方案
弹出此错误的原因是因为您将event
对象传递给setCounterKey
事件onClick
:
function CounterParent() {
const [counterKey, setCounterKey] = React.useState(0);
return (
<div>
// onClick={setCounterKey} will pass the event object to setCounterKey
// onClick={(e => setCounterKey(e)} <-- `e` is event object
// Instead use functional update like so
<button onClick={() => setCounterKey(p => p + 1)}>reset</button>
<Counter key={counterKey} />
</div>
);
}
这是一种不好的做法,警告本身和文档中解释了原因。
另一方面,使用useReducer
,setCounterKey
已经使用回调调用 ( c => c + 1
) 定义,因此事件未通过。
可以通过在此处useState
查看示例来制作确切的示例。
我们应该调用具有我们想要的动作类型和有效负载的对象吗?
const [state, dispatch] = useReducer(reducer, initialArg, init);
不。传递一个对象type
是一种常见的 Redux 模式。它确实令人困惑,但reducer
功能可以是任何东西。参考useReducer
文档。
推荐阅读
- html - 如何使工具提示出现在下方而不是覆盖它?
- python - 检查一个单词是否在元组列表中至少出现两次?
- r - 如何将自定义函数应用于我的数据框的每一列
- angular - 如何为自定义 Angular 验证器提供异步参数
- angular - Typescript 对象动态分配更改字段名称
- python - 如何为用户创建选择某个类别的机会,并打印出结果
- c# - 使用 Sharepoint CSOM,如何在按 Id 检索内容类型时检查 null
- android - requestLocationUpdates() 在真正的智能手机上不起作用
- c# - 如何使用 Azure 服务总线配置 EventBusServiceBus?
- python - 在 WHERE 子句中传递一个列表 python mysql