我正在尝试使用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>
)
答案 0 :(得分: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)
的值,以便确保正确更新状态。