yield [] 和 yield all() 之间的区别 - ES6/redux-saga
Difference between yield [] & yield all() - ES6/redux-saga
使用 redux-saga 的 yield all([])
比 ES6
的内置 yield []
有什么优势吗?
为了运行多个并行操作,redux-saga建议:
const result = yield all([
call(fetchData),
put(FETCH_DATA_STARTED),
]);
但不用 all()
方法也可以完成同样的事情:
const result = yield [
call(fetchData),
put(FETCH_DATA_STARTED),
];
哪个更好,为什么?
没有功能差异,正如 Mateusz Burzyński(redux-saga 维护者)解释的那样 here:
Under the hood they are both the same, yield [...effects]
will result in a deprecation warning though and inform you about all
.
This was introduced to make parallel behaviour explicit and it nicely mirrors Promise.all
最好使用 all()
,因为它会通知 reader 我们在这里产生了不止一种效果,但是没有它,yield 的各种用途仍然有效:
生成具有多重效果的对象
const { company, profile } = yield {
company: select(getCompany),
profile: select(getUserProfile, userId),
};
生成数组文字
yield [
put(userRequestSucceeded(userId)),
put(userReceived(response.data)),
];
使用映射生成数组
yield userIds.map(userId => call(fetchUserDetails, userId));
使用 redux-saga 的 yield all([])
比 ES6
的内置 yield []
有什么优势吗?
为了运行多个并行操作,redux-saga建议:
const result = yield all([
call(fetchData),
put(FETCH_DATA_STARTED),
]);
但不用 all()
方法也可以完成同样的事情:
const result = yield [
call(fetchData),
put(FETCH_DATA_STARTED),
];
哪个更好,为什么?
没有功能差异,正如 Mateusz Burzyński(redux-saga 维护者)解释的那样 here:
Under the hood they are both the same,
yield [...effects]
will result in a deprecation warning though and inform you aboutall
.This was introduced to make parallel behaviour explicit and it nicely mirrors Promise.all
最好使用 all()
,因为它会通知 reader 我们在这里产生了不止一种效果,但是没有它,yield 的各种用途仍然有效:
生成具有多重效果的对象
const { company, profile } = yield {
company: select(getCompany),
profile: select(getUserProfile, userId),
};
生成数组文字
yield [
put(userRequestSucceeded(userId)),
put(userReceived(response.data)),
];
使用映射生成数组
yield userIds.map(userId => call(fetchUserDetails, userId));