简体   繁体   English

Redux-thunk动作

[英]Redux-thunk actions

I have actions/index.js file with action creators, and I am using redux-thunk as middleware. 我有带有动作创建者的actions / index.js文件,并且我在使用redux-thunk作为中间件。 This is the code: 这是代码:

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})
};

And I have a question. 我有一个问题。 Should I write action creators, which do not send a request to external API (for example, scrollMovement and selectConfig), at the same style, as I write hadleToken, submitSurvey, and fetchUser action creators? 我应该以与编写hadleToken,submitSurvey和fetchUser操作创建者相同的样式编写不向外部API发送请求(例如,scrollMovement和selectConfig)的操作创建者吗?

I hope that you understand my question. 我希望你能理解我的问题。 If not, add comments, I will explain. 如果没有,请添加评论,我会解释。

For an a synchronous flow of data, you just need to return an object as normal you do, because, under the hood, thunk middleware intercepts actions of the type function before the dispatch is generated. 对于同步数据流,您只需要像平常一样返回一个对象,因为在内部,thunk中间件在生成分派之前会拦截类型函数的操作。

So for scrollMovement and selectConfig you don't have to return a function because these follow an a synchronous flow of data 因此,对于scrollMovementselectConfig您不必返回函数,因为它们遵循同步数据流

export const scrollMovement = scrollValue => {
    return {type: SCROLL_MOVE, payload: scrollValue}
};

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM