首页 > 解决方案 > 为什么我们需要 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>
  );
}

标签: javascriptreduxes6-promiseredux-thunk

解决方案


推荐阅读