javascript - React useState 的 setter 是否会过时?
问题描述
我正在使用全局事件处理程序。为了避免在每次状态更改时分离/重新附加事件处理程序,我使用带有强制更新的 ref:
const ref = useRef();
const forceUpdate = useState()[1];
const handlePopState = (event) => {
ref.current = {
...ref.current,
foo: event.foo,
};
forceUpdate();
};
useEffect(() => {
window.addEventListener('popstate', handlePopState);
return () => {
window.removeEventListener('popstate', handlePopState);
};
}, []);
我很惊讶这实际上有效。从技术上讲,forceUpdate
正在使用useState
's setter 的陈旧版本,但这似乎不会导致错误。
使用这样的旧版本是否安全useState
?如果不是,这会导致什么问题?
解决方案
使用这样的旧版本是否安全
useState
?
是的,这就是你this.forceUpdate
使用钩子实现的方式。
通常你会看到类似的东西:
// forceRender();
const [, forceRender] = useReducer((p) => !p, false);
它甚至用于react-redux
源代码。
推荐阅读
- scala - Scala 运行时编译:如何获取错误消息的行号?
- r - 根据 dplyr 中的条件查找组之间的差异
- spss - SPSS Merge 基于标签的输出表
- r - R - 具有两个 Y 轴的 ggplot
- r - 如何将线性回归的置信区间添加到具有多个组的图中
- python - 试图从一个城市的一系列可能温度中获得一个随机温度
- python - 我拥有的两个 Gmail 帐户之间从 Python SMTP 服务器发送的简单电子邮件被标记为垃圾邮件。我该如何解决?
- node.js - 带有健康检查的nestjs enableCors
- java - Jenkins - Java CLASSPATH 未正确加载
- java - 如何从 IP 地址解析出八位字节,存储为 int 变量,然后使用预先提供的驱动程序方法返回