2016-11-02 90 views
1

我想用axios加載數據,但無法將數據提取到狀態。異步操作返回數組[0]

我減速機:

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

const initialState = { 
    fetching: false, 
    fetched: false, 
    questions: [], 
    error: null, 
} 

export default function reducer(state = initialState, action = {}) { 
    switch (action.type) { 
    case types.FETCH_QUESTIONS_SUCCESS: 
     return { 
     ...state, 
     questions: action.payload 
     }; 
    case types.FETCH_QUESTIONS_FAILURE: 
     return { 
     ...state, 
     error: action.payload 
     }; 
    default: 
     return state; 
    } 
} 

我的行動的創建者:

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

export function fetchQuestions(city) { 
    return function (dispatch) { 
    axios.get('http://rest.learncode.academy/api/test123/tweets') 
     .then((response) => { 
     console.log("Test:" + response.data) //This returns [Object Object] 
     dispatch({type: "FETCH_QUESTIONS_SUCCESS", payload: response.data}) 
     }) 
     .catch((err) => { 
     dispatch({type: "FETCH_QUESTIONS_FAILURE", payload: err}) 
     }) 
    } 
}; 

中的console.log在那裏確實給我[對象對象。但是,當我打電話的動作不會放任何東西的狀態questions

const {questions, actions} = this.props; 
const openQuestionOverview = (test) => { 
    actions.fetchQuestions(); 
    console.log(questions); //Returns Array[0] for questions 
} 

return(
    <TouchableHighlight onPress={openQuestionOverview}> 
       <Image source={button} /> 
    </TouchableHighlight> 
) 
+0

'types.FETCH_QUESTIONS_SUCCESS'的值是什麼? – QoP

回答

1

它返回[Object Object]事實是不是一個問題......這就是對象的字符串字面表示。出於調試的目的,您可能希望將其註銷到兩行或與字符串化的JSON連接。

console.log('Test') 
console.log(response.data) 

// or 

console.log('Test: ' + JSON.stringify(response.data)) 

假設響應數據包含questions鍵後,馬上fetchQuestions應返回[],因爲這是初始狀態和API是異步的日誌。因此,您將無法在您調用該操作的同一調用中看到該狀態。您可能想要將Text組件綁定到值JSON.stringify(questions,null,2),以確保狀態正確更新。

+1

非常感謝,事實上是因爲我之後調用了'console.log()'。而不是我在構造函數中調用'fetchQuestions()'函數,然後在按下按鈕時調用console.log()。 –