使用react/redux的API调用返回空对象

问题描述:

Im新增React和Redux,但仍有点困惑。使用react/redux的API调用返回空对象

我的目标是通过使用GET请求呈现HTML中的json数据。我使用的是反应和Redux的管理对象的状态,但我相信我的问题是,该数据甚至不存在

这里是代码:

Action.js:

import axios from 'axios'; 
export function fetchUsers(){ 
const request=axios.get('https://randomuser.me/api/'); 
return(dispatch)=>{ 
    request.then(({data})=>{ 
     dispatch({type:'FETCH_PROFILES',payload:data}) 

    }); 
}; 



} 

Component.js:

import React,{Component} from 'react'; 
 
import {connect} from 'react-redux'; 
 
import * as actions from '../actions'; 
 

 

 
class App extends Component { 
 

 
\t ComponentWillMount() { 
 
\t \t this.props.dispatch(onFetchUser()); 
 
\t } 
 
\t \t render() { 
 
    
 
    
 
    const mappedUsers = this.props.users.map(user => <li>{user.email}</li>) 
 

 
    return <div> 
 
     
 
     <ul>{mappedUsers}</ul> 
 
    </div> 
 
    } 
 
\t \t 
 
\t } 
 
const mapStateToProps = (state) => { 
 
    return { 
 
    users: state.users.users 
 
    } 
 
} 
 

 
const mapDispatchToProps = (dispatch) => { 
 
    return { 
 
    onFetchUsers:() => dispatch(fetchUsers()) 
 
    }; 
 
} 
 
export default connect(mapStateToProps, mapDispatchToProps)(App);

CombineReducer.js:

import { combineReducers } from "redux" 
 

 
import users from "./reducer-active-user" 
 

 

 
export default combineReducers({ 
 

 
    users , 
 
})

Reducer.js:

const initialState = { 
 
    users: [] 
 
}; 
 
export default function reducer(state= initialState 
 
    , action) { 
 

 

 
    switch(action.type){ 
 
     case 'FETCH_PROFILES': 
 
      return { 
 
     users: action.payload, 
 
     } 
 
     break; 
 
      
 
    } 
 
    return state; 
 
}

任何帮助,将不胜感激。

你应该在爱可信.then回调返回调度,因为它的一个async呼叫

import axios from 'axios'; 
export function fetchUsers(){ 
     return function(dispatch) { 
         return axios.get('https://randomuser.me/api/') 
         .then(({data}) => { 
          dispatch({type:'FETCH_PROFILES',payload:data}) 
         }); 

     } 

} 

另外,在您的组件需要调用onFetchUsers

class App extends Component { 

    componentWillMount() { 
     this.props.onFetchUsers() 
    } 
    render() { 


    const mappedUsers = this.props.users.map(user => <li>{user.email}</li>) 

    return (<div> 
       <ul>{mappedUsers}</ul> 
      </div> 
     ) 
    } 

} 
+0

没有改变,仍然会返回空对象 –

+0

现在尝试解决方案 –

+0

仍然没有,但由于某种原因,我认为问题是组件 –