2017-05-25 61 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