javascript - 为什么我们需要 Redux-Thunk 来处理异步流而不是直接使用 Promise?
问题描述
我已经搜索了这个问题的答案,但答案很模糊,我仍然不明白为什么我们需要 Redux-Thunk 而不是 Promise 来处理异步流。
请帮忙看看我下面的一段代码。
export default function CalculationPage() {
const value = useSelector((state) => state.value);
const dispatch = useDispatch();
const handleIncreaseClick = () => {
// This is a thunk
const increaseValue = () => (dispatch) => {
fetch().then(() => dispatch({ type: 'INCREMENT' }));
};
dispatch(increaseValue());
// Why can't we use Promise directly?
// fetch().then(() => dispatch({ type: 'INCREMENT' }))
};
const handleDecreaseClick = () => {
dispatch({ type: 'DECREMENT' });
};
return (
<div>
<span className='calculation_value'>value: {value}</span>
<div>
<button className='calculation_button' onClick={handleIncreaseClick}>
Increase
</button>
<button className='calculation_button' onClick={handleDecreaseClick}>
Decrease
</button>
</div>
</div>
);
}
解决方案
推荐阅读
- ios - 表格视图删除行和部分
- amazon-neptune - 将数据加载到 Amazon Neptune 数据库
- jsonata - 如何在确保结果仍然是 jsonata 中的数组的同时从数组中删除第一个元素?
- angular - Angular 9. 组件是 Sample 类,但不是 SampleExtended,尽管它是作为 SampleExtended 创建的
- rust - 了解生命周期:最大生命周期和“静态”
- c# - 批量更新行值 ASP.NET Core C# 控制台应用程序
- javascript - 如何在结果中获得正确的值?(计算器js)
- python - 读取图像并进行颜色更改(使用 Image 或 openCV)(Python)
- angular - this.sanitizer.bypassSecurityTrustResourceUrl 在使用 ngx-image-cropper 时不是一个函数
- r - R中的错误:替换有......行,数据有......行