异步操作 returns 数组 [0]

Async action returns Array[0]

我正在尝试使用 axios 加载数据,但无法将数据提取到状态中。

我的减速器:

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确实给了我[Object Object]。但是当我调用动作时,它不会在状态 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>
)

它 returning [Object Object] 的事实不是问题...那是对象的字符串文字表示。出于调试目的,您可能希望在两行中将其注销或与字符串化 JSON.

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

// or 

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

假设响应数据包含 questions 键,fetchQuestions 之后的日志应该 return [] 因为那是初始状态 API是异步的。因此,您将无法在调用操作的同一个调用中看到状态。您可能希望将 Text 组件绑定到 JSON.stringify(questions,null,2) 的值,以便您可以确保正确更新状态。