2017-05-25 58 views
0

当我尝试访问我的组件中的响应对象时,它不会给我一个错误,但它不会打印。我确实可以访问组件中的响应,但那就是它,我实际上不能打印某些内容。无法通过this.props |访问响应对象React/Redux

操作文件

import axios from 'axios'; 
import { FETCH_USERS, FETCH_USER } from './types'; 


const BASE_URL = "http://API_URL/endpoint/" 
export function fetchUsers(id,first_name, last_name, dob) { 
    const request = axios.post(`${BASE_URL}member-search?patientId=${id}&firstName=${first_name}&lastName=${last_name}&dateOfBirth=${dob}&length=10`).then(response => { return response; }) 

    return { 
    type: FETCH_USERS, 
    payload: request 
    }; 
} 

export function fetchUser(id) { 
    const request = axios.get(`${BASE_URL}members/${id}/summary/demographics`).then(response => { return response; }) 

    return{ 
     type: FETCH_USER, 
     payload: request 
    }; 
} 

我减速器文件

import _ from 'lodash'; 
import { 
    FETCH_USERS, FETCH_USER 
} from '../actions/types'; 

export default function(state = [], action) { 
    switch (action.type) { 
    case FETCH_USER: 
     return { ...state, [action.payload.data.member.id]: action.payload.data.member }; 
     // return [ action.payload.data.member, ...state ]; 
    case FETCH_USERS: 
     return _.mapKeys(action.payload.data.searchResults, 'id'); 
    } 

    return state; 
} 

最后我的部件,其中我试着去渲染响应的一些成果。

import React, { Component } from 'react'; 
import { connect } from 'react-redux'; 
import { Link } from 'react-router-dom'; 
import { fetchUser } from '../actions'; 



class PatientWrapper extends Component{ 
    componentDidMount() { 
    const { id } = this.props.match.params; 
    this.props.fetchUser(id); 

    } 
    render(){ 
    const { user } = this.props; 
    console.log('this.props response: ',user); 

    if(!user){ 
     return <div>loading...</div>; 
    } 

    return(
     <div> 
     Name: {user.firstName} 
     Last Name: {user.lastName} 
     </div> 
    ) 
    } 
} 
function mapStateToProps({ users }, ownProps) { 
    // return { users }; 
    return { user: users[ownProps.match.params.id] }; 
} 
export default connect (mapStateToProps, { fetchUser })(PatientWrapper); 

我上传的响应的屏幕截图IMG:http://prntscr.com/fbs531

什么是错我的代码?

+0

根据您的屏幕截图,它会显示它正好记录到控制台。有什么问题? –

回答

0

问题是,在fetchUser操作中,您使用Promise并将其返回到有效内容字段中。此承诺不包含任何您需要的信息,例如响应数据。因此,要解决问题,只有在检索到响应时才需要调度操作(例如,在then成功回调中)。

要实现它,你需要通过mapDispatchToProps在第二个参数中connect功能,为您的组件,并通过调度功能到你的动作:

function mapDispatchToProps(dispatch) { 
    return { 
     fetchUser: id => fetchUser(id, dispatch) 
    } 
} 

然后在操作只是做以下

function fetchUser(id, dispatch) { 
    const request = axios.get(`${BASE_URL}/${id}`) 
     .then(response => dispatch({ 
      type:FETCH_USER, 
      payload: response 
     })); 
} 

有关完整的示例,请参阅JSFiddle

+0

是的,那是我想念的,非常感谢! – Emmanuel