Reactjs 异步操作返回数组[0]
我正在尝试使用axios加载数据,但无法将数据提取到状态 我的减速机:Reactjs 异步操作返回数组[0],reactjs,asynchronous,react-native,redux,axios,Reactjs,Asynchronous,React Native,Redux,Axios,我正在尝试使用axios加载数据,但无法将数据提取到状态 我的减速机: import * as types from '../actions/actionTypes'; const initialState = { fetching: false, fetched: false, questions: [], error: null, } export default function reducer(state = initialState, action
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]。但是,当我调用该操作时,它不会将任何内容放入状态问题
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>
)
const{questions,actions}=this.props;
常量openQuestionOverview=(测试)=>{
actions.fetchQuestions();
console.log(questions);//返回问题的数组[0]
}
返回(
)
它返回的事实[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)
的值,以便确保状态正确更新。类型的值是多少。获取问题\u成功
?非常感谢,这确实是因为我刚刚调用了控制台.log()
。相反,我在构造函数中调用了fetchQuestions()
函数,然后在按下按钮时调用了console.log()。