2017-08-30 142 views
0

使用React和Redux,我需要等待我的所有動作都被執行才能更新組件狀態。閱讀Axios文檔,我發現axios.all收集我所有的動作,並等待所有的動作得到解決(基本上我調用一個API n次獲得有關n項的信息)。 問題是,axios.all的.then函數內的console.log根本沒有返回任何內容,但操作調度正確。Axios.all在componentWillReceiveProps中沒有調用

if (this.props.evaluation && this.props.evaluation.topics) { 
    var promises = [] 

    var array = this.props.evaluation.topics; 
    var selectedArray = [] 
    for (var i = 0; i < array.length; i++) { 
    promises.push(this.props.fetchTopic(array[i])) 
    } 

    axios.all(promises).then(function(results) { 
    results.forEach(function(response) { 
     console.log('///////////////////////'); 
     console.log(response.value); 
     console.log('///////////////////////'); 
    }) 
    }); 
} 

編輯:這是我fetchTopic代碼

在我的組件:

const mapDispatchToProps = (dispatch) => ({ 
    fetchTopic: (id) => dispatch(fetchTopic(id)), 
}) 

在我actions.js

export const fetchTopic = (id) => ({ 
    type: "FETCH_TOPIC", 
    payload: axios.get(process.env.SERVICE_URL + '/topic/' + id, { headers: { 'Authorization': 'JWT ' + sessionStorage.jwt }}) 
}) 
+0

添加'fetchTopic'代碼。確保它返回一個承諾。 –

+0

操作創建者必須返回普通的JavaScript對象,你的是在不會工作的有效載荷中返回一個axios調用 –

回答

0

更改此

export const fetchTopic = (id) => ({ 
    type: "FETCH_TOPIC", 
    payload: axios.get(process.env.SERVICE_URL + '/topic/' + id, { headers: { 'Authorization': 'JWT ' + sessionStorage.jwt }}) 
}) 

這個

export const fetchTopic = (id, cb) => { 
    axios.get(process.env.SERVICE_URL + '/topic/' + id, { headers: { 'Authorization': 'JWT ' + sessionStorage.jwt }}) 
    .then((response) => { 
     if (cb) cb({ type: "FETCH_TOPIC", payload:response }) 
    }); 
    } 

和運行

for (var i = 0; i < array.length; i++) { 
    this.props.fetchTopic(array[i], (result) => { 
    // get the result here 
    }) 
} 
相關問題