如何使用react,redux,axios响应发送动作

时间:2016-03-23 19:33:43

标签: javascript reactjs redux axios

我想获得从post返回到有效负载的响应。如何将返回的结果发送给action.How可以这样做吗?

import axios from 'axios';
import * as types from './actionTypes';

const ROOT_URL = `http://localhost:8000`;

export function addPost(title){
    const url = `${ROOT_URL}/api/v1/post/`;
    var request;

    axios.post(url, {
        title: title,
    }).then(function (response) {
        request = response;
    })
    .catch(function (response) {
        request = response;
    });

    console.log(request);

    return {
        type:types.ADD_POST,
        payload:request
    }
}

1 个答案:

答案 0 :(得分:1)

一种方法是使用一个单独的服务来调用适当的操作:

这样的东西
export function addPost(title){
    return {
        type:types.ADD_POST,
        payload:request
    }
}

export function addPostService(title){
    const url = `${ROOT_URL}/api/v1/post/`;
    var request;

    axios.post(url, {
        title: title,
    }).then(function (response) {
        dispatch(addPost(response.body))
    })
    .catch(function (response) {
        request = response;
    });
}

如果您想要更高级的解决方案,请查看redux-thunk:https://github.com/gaearon/redux-thunk