在一个特性请求中,我需要检测刷事件并相应地更改dom上的一些内容。所以我决定使用锤子,并给它一个反应钩的机会。但我不明白在下面的代码中闭包是如何工作的。有人能解释为什么左右处理程序总是使用状态对象的第一个值吗?
医生:不能用刷卡正确地更换计数器。最多只能达到-1或1分钟
const App = () => {
const elm = useRef(null);
const [counter, setCounter] = useState(0);
const [obj, setObj] = useState({ counter: 0 });
const [mounted, setMounted] = React.useState(false);
React.useLayoutEffect(() => {
if (!mounted && elm.current) {
const h = new Hammer(elm.current);
h.on("swipeleft", () => setCounter(counter + 1));
h.on("swiperight", () => setCounter(counter - 1));
h.on("swipeleft", () => setObj({ counter: obj.counter + 1 }));
h.on("swiperight", () => setObj({ counter: obj.counter - 1 }));
setMounted(true);
}
});
return (
<div
ref={elm}
style={{ width: "300px", height: "300px", backgroundColor: "orange" }}
>
<p>This is a swipeable content area</p>
<p>Counter: {counter}</p>
<p>Obj counter: {obj.counter}</p>
</div>
);
};发布于 2019-01-16 11:43:06
Hammer对象的回调范围在第一次呈现时只捕获一次。不重要的是,如果值发生变化,作用域将与初始值一起保留。要避免此问题,可以使用功能形式更新您的值。
h.on("swipeleft", () => setCounter(previousCounter => previousCounter + 1);https://stackoverflow.com/questions/54216268
复制相似问题