【问题标题】:Redux-thunk actionsRedux-thunk 操作
【发布时间】:2018-03-20 23:20:37
【问题描述】:

我有带有动作创建者的动作/index.js 文件,并且我使用 redux-thunk 作为中间件。这是代码:

export const fetchUser = () => async dispatch => {
    const res = await axios.get('/api/current_user');
    dispatch({type: FETCH_USER, payload: res.data});
};

export const handleToken = (token) => async dispatch => {
    const res = await axios.post('/api/stripe/', token);

    dispatch({type: FETCH_USER, payload: res.data});
};

export const submitSurvey = (values, history) => async dispatch => {
    const res = await axios.post('/api/Surveys', values);

    history.push('/Surveys');
    dispatch({type: FETCH_USER, payload: res.data});
};

export const scrollMovement = (scrollValue) => dispatch => {
    dispatch({type: SCROLL_MOVE, payload: scrollValue})
};

export const selectConfig = (id) => dispatch => {
  dispatch({type: "SELECT_CONFIG", payload: id})
};

我有一个问题。我是否应该以与我编写 hadleToken、submitSurvey 和 fetchUser 动作创建者相同的风格编写不向外部 API(例如,scrollMovement 和 selectConfig)发送请求的动作创建者?

希望您能理解我的问题。如果没有,添加cmets,我会解释。

【问题讨论】:

    标签: reactjs ecmascript-6 redux redux-thunk


    【解决方案1】:

    对于一个同步的数据流,你只需要像往常一样返回一个对象,因为在后台,thunk 中间件会在生成调度之前拦截类型函数的动作。

    所以对于scrollMovementselectConfig,您不必返回函数,因为它们遵循同步的数据流

    export const scrollMovement = scrollValue => {
        return {type: SCROLL_MOVE, payload: scrollValue}
    };
    
    export const selectConfig = id => {
      return {type: "SELECT_CONFIG", payload: id}
    };
    

    【讨论】:

    • dispatch 未定义
    • 但是 dispatch 在这种情况下是未定义的,是的
    • 是的,对不起,我编辑了我的帖子,如果您遵循同步流程,您只需要返回一个作为您操作的对象。
    猜你喜欢
    • 1970-01-01
    • 2018-01-31
    • 2018-09-22
    • 2016-08-06
    • 1970-01-01
    • 2019-12-17
    • 2016-11-23
    • 2017-02-01
    • 2017-03-03
    相关资源
    最近更新 更多