2016-03-23 66 views
0

我想獲得從post發回到payload的響應。如何將返回的結果發送到action.How可以這樣做嗎?如何響應發送使用react,redux,axios到動作

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 
    } 
} 
+0

超級有用:http://redux.js.org/docs/advanced/AsyncActions.html – lux

回答

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

如果你想要一個更先進的解決方案,檢查出終極版-的thunk:https://github.com/gaearon/redux-thunk

+0

好的。非常感謝你的幫助 – onerciller

相關問題