首页 > 解决方案 > 是否可以在 Redux Store 中实现 setTimeout?

问题描述

我想知道是否可以在 Redux Store 中存储一个 setTimeout 并让 setTimeout 触发一个偶数。据我所知,动作是 javascript 对象,但我不确定它将如何与商店交互。

最初我在想这样的事情

const timer = setTimeout(() => {someFunc}, 1000);

行动:

const t = (timer) => {
  return {
    type:TIMER_START,
    timer
  }
};

减速器:

tReducer = (state={timer:null}, action) => {
  switch(action.type) {
    case TIMER_START:
      return {...state, timer: action.timer}
    default:
      return state;
  }
};

这是在商店中实现超时的有效方法吗?如果是这样,是否可以取消超时?由于我们想要 Redux 中的纯函数,我不确定我们是否可以取消超时

标签: reactjsreduxreact-reduxsettimeout

解决方案


动作必须是普通对象,没有副作用。要调度异步操作,您应该使用自定义中间件,例如redux-sagaor redux-thunk。异步操作的示例redux-thunk

const storeUsers = () =>{
    return dispatch =>{
        setTimeOut(() => dispatch({type: 'SENDED_AFTER_3_SECONDS'}), 3000)
    }
}

推荐阅读