【问题标题】:Dispatching an action in a debounced function using redux-thunk使用 redux-thunk 在去抖动函数中调度动作
【发布时间】:2017-06-12 23:15:39
【问题描述】:

我有以下去抖函数,每次用户输入用户名字段时都会调用该函数。它按预期工作。

export const uniqueUsernameCheck = _.debounce(({ username }) => {
  axios.post(`${API_URL}/signup/usernamecheck`, { username })
    .then((res) => {
      console.log('Is unique?', res.data.status);
    })
    .catch((error) => {
      console.log(error);
    });
}, 500); 

但是,我正在尝试使用 redux-thunk 修改函数,以便可以在函数中调度操作。这就是我所拥有的:

export const uniqueUsernameCheck = _.debounce(({ username }) => {
  console.log('I can see this');
  return (dispatch) => {
    console.log('But not this');
    dispatch({ type: USERNAME_CHECK });
    axios.post(`${API_URL}/signup/usernamecheck`, { username })
      .then((res) => {
        dispatch(authError(res.data.error));
      })
      .catch((error) => {
        console.log(error);
      });
  };
}, 500);

问题在于上面的代码不再像初始函数那样触发我的发布请求,并且没有任何东西被分派。我知道我做错了什么,但不知道是什么。

编辑:

这就是我建立商店的方式

const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));

【问题讨论】:

    标签: javascript reactjs redux react-redux redux-thunk


    【解决方案1】:

    看看这个:

    http://codepen.io/anon/pen/egeOyJ

    const userService = _.debounce(username => {
      setTimeout(
        ()=>{
          console.log('userService called after debounce. username:', username)
        }
        ,1000)
    }, 500)
    
    const uniqueUsernameCheck = (username) => (dispatch) => {
      console.log('I can see this')
      userService(username)
    }
    
    console.log('begin')
    const reducers = (action) => {console.log(action)}
    const store = Redux.createStore(
      reducers, 
      {}, 
      Redux.applyMiddleware(ReduxThunk.default))
    
    store.dispatch(uniqueUsernameCheck('rafael'))
    store.dispatch(uniqueUsernameCheck('rafael'))
    store.dispatch(uniqueUsernameCheck('rafael'))
    

    【讨论】:

    • 两个注意事项:必须调度一个直接接收'dispatch'的函数;您必须只创建一次去抖动功能。
    猜你喜欢
    • 2020-03-06
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 2018-05-21
    • 2021-01-03
    • 2020-03-25
    • 2017-04-27
    • 2017-09-28
    相关资源
    最近更新 更多