- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
为了防止对未安装的 React 组件进行幻像更新,React 会告诉您 cancel any pending promises卸载时在组件上(例如获取附加数据的 promise )。使用 Bluebird Promise 很容易做到这一点,它有一个 .cancel()
导致 .then()
的方法和 .catch()
处理程序从不响应。
但是,ES6 Promises 不支持取消。另外,ES7 的 async
和 await
仅使用原生 Promises,不支持任何插入式替换(例如 Bluebird)。这意味着如果你想在 React 中取消 Promise,就像他们告诉你的那样,你必须使用 .then()
和 .catch()
并且还必须在本地 Promise 方法上放置一个中间人,例如 fetch()
以便可以取消。
这真的是 React 所期望的吗?
最佳答案
仅供引用。
使用 CPromise 包,您可以取消您的 promise 链,包括嵌套的。它支持 AbortController 和生成器作为 ECMA 异步函数的替代品。目前该项目处于测试阶段。
生成器使用 Live Demo :
import CPromise from "c-promise2";
const chain = CPromise.resolve()
.then(function* () {
const value1 = yield new CPromise((resolve, reject, { onCancel }) => {
const timer = setTimeout(resolve, 1000, 3);
onCancel(() => {
console.log("timer cleared");
clearTimeout(timer);
});
});
// Run promises in parallel using CPromise.all (shortcut syntax)
const [value2, value3] = yield [
CPromise.delay(1000, 4),
CPromise.delay(1000, 5)
];
return value1 + value2 + value3;
})
.then(
(value) => {
console.log(`Done: ${value}`); // Done: 12 (without calling cancel)
},
(err) => {
console.log(`Failed: ${err}`); // Failed: CanceledError: canceled
}
);
setTimeout(() => chain.cancel(), 100);
输出:
timer cleared
Failed: CanceledError: canceled
那里的所有阶段都是完全可取消/可中止的。
export class TestComponent extends React.Component {
state = {};
async componentDidMount() {
console.log("mounted");
this.controller = new CPromise.AbortController();
try {
const json = await this.myAsyncTask(
"https://run.mocky.io/v3/7b038025-fc5f-4564-90eb-4373f0721822?mocky-delay=2s"
);
console.log("json:", json);
await this.myAsyncTaskWithDelay(1000, 123); // just another async task
this.setState({ text: JSON.stringify(json) });
} catch (err) {
if (CPromise.isCanceledError(err)) {
console.log("tasks terminated");
}
}
}
myAsyncTask(url) {
return CPromise.from(function* () {
const response = yield cpFetch(url); // cancellable request
return yield response.json();
}).listen(this.controller.signal);
}
myAsyncTaskWithDelay(ms, value) {
return new CPromise((resolve, reject, { onCancel }) => {
const timer = setTimeout(resolve, ms, value);
onCancel(() => {
console.log("timeout cleared");
clearTimeout(timer);
});
}).listen(this.controller.signal);
}
render() {
return (
<div>
AsyncComponent: <span>{this.state.text || "fetching..."}</span>
</div>
);
}
componentWillUnmount() {
console.log("unmounted");
this.controller.abort(); // kill all pending tasks
}
}
Using Hooks and cancel
method
import React, { useEffect, useState } from "react";
import CPromise from "c-promise2";
import cpFetch from "cp-fetch";
export function TestComponent(props) {
const [text, setText] = useState("fetching...");
useEffect(() => {
console.log("mount");
const promise = cpFetch(props.url)
.then(function* (response) {
const json = yield response.json();
setText(`Delay for 2000ms...`);
yield CPromise.delay(2000);
setText(`Success: ${JSON.stringify(json)}`);
})
.canceled()
.catch((err) => {
setText(`Failed: ${err}`);
});
return () => {
console.log("unmount");
promise.cancel();
};
}, [props.url]);
return <p>{text}</p>;
}
关于javascript - React.js 告诉你取消 promise 。官方 promise 不能取消。我应该怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59568434/
今天上午据小米穿戴官方消息,为了保障更好的使用体验和更充足的备货,小米手表尊享版将延期至2020年2月开售。 据了解,早在今年11月初小米正式发布小米手表,共有标准版和尊享版两个版本,价格分别为1
我的意思是,如果我可以运行例如官方 docker 镜像 DEBIAN 并在此之上 运行具有相同支持架构的官方 docker 镜像 NGINX,例如Linux x86-64? 它会像我以非 docker
在 .NET 3.5 中,大量扩展方法被添加到核心代码库中。我注意到在 MSDN 中,IEnumerable<> 等添加了有关扩展方法的部分。 是否有已添加的所有扩展方法的列表以供引用? 编辑感谢您的
在vertx指南中,链接异步调用的顺序组合如下所示: FileSystem fs = vertx.fileSystem(); Future startFuture = Future.future();
neo4j 文档有 this page about creating unit tests for neo4j. 本质上它建议我们创建一个模拟数据库使用 graphDb = new TestGraph
我是 C++ 的新手,我想了解链接器是如何正式工作的。我正在使用 Linux Mint 16。是否存在 ld 链接器官方规范? 最佳答案 您可能会对链接器和共享库有更多了解 here还有here是 l
已关闭。此问题旨在寻求有关书籍、工具、软件库等的建议。不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以
我想创建一个自定义 Android 汽车应用程序,而不会分散驾驶员的注意力。我浏览了很多博客和网站,发现自 3.0 版本以来曾经有一些自定义应用程序被屏蔽。这些自定义应用程序的开发人员使用的是非官方的
我刚找到 this Project就像。嘿。为什么不尝试使用它呢? 所以。刚刚下载它(我没有做任何更改!),打开 Android Studio,运行它,然后遇到以下问题。 error: cannot
Docker 的官方 Postgres 镜像使用两个环境变量:POSTGRES_USER 和 POSTGRES_PASSWORD 参数化数据库创建: https://registry.hub.dock
我刚刚从 Python download page 下载了 Python 2.7.3 64 位安装程序我想验证签名。所以我需要导入 key ,我的首选方法是从受信任的 key 服务器获取它们。 Pyt
当我安装 Andoird 5.0 SDK 并导入 Camera2Basic 示例源代码时。CameraDevice.StateListener 和 CameraCaptureSession.State
在Design Philosophy节official Fragment guide ,它说: You should design each fragment as a modular and reu
我正在使用 Roslyn 编写一个应用程序来从语法和语义上分析 C# 源代码。对于正在分析的源代码中定义的每种类型,我想存储它是引用类型(类)、值类型(结构)还是接口(interface)。 类型的类
有没有官方的 XSLT 验证器,比如 http://validator.w3.org/用于 HTML 和 XHTML? 我知道http://validator.w3.org/也可用于验证 XML 和
我主要使用 C++ 进行科学计算,最近我一直将自己限制在一个非常类似于 C 的 C++ 特性子集;即,除了复杂和 STL 之外没有类/继承,模板仅用于查找/替换各种替换,以及其他一些我无法用语言表达的
我了解到Google会根据访问它的浏览器/设备来自动提供 TTF , EOT , WOFF 或 SVG 字体文件。 现在,我计划从服务器本身托管和提供字体文件,为此,我首先必须下载Web字体的所有文件
他们有什么不同? 例如,与官方 SDK 相比,选择 libfreenect 或 OpenNI+SensorKinect 有什么优势,反之亦然? 有什么缺点? 最佳答案 请注意,以下答案是按日期计算的,
我想使用官方的 Hashicorp 镜像来运行 Terraform 而不是手动安装。我已经关注了 dockerhub 上的文档,但没有关于如何在何处安装卷的任何详细信息 - 例如在当前目录中使用“ma
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。 关闭 5 年前。
我是一名优秀的程序员,十分优秀!