2017-09-14 13 views
-1

は私のコードです:還元剤は空のオブジェクトを返すのですか?ここ

アクションの作成者

export function fetchHead() { 

    const url = HEAD_URL; 

    const request = axios.get(url); 

    return { 

    type: FETCH_HEAD, 

    payload: request 

    }; 
} 

リデューサー

import { FETCH_HEAD } from '../actions'; 

import _ from 'lodash'; 

export default function(state = {}, action) { 

    switch (action.type) { 

    case FETCH_HEAD: 

     return _.mapKeys(action.payload.data.articles, 'id'); 

    default: 

     return state; 
    } 

} 

減速キー、

import { combineReducers } from 'redux'; 


import HeadReducer from './head_reducer'; 

const rootReducer = combineReducers({ 


    heads: HeadReducer 

}); 

export default rootReducer; 
を約束しますの

コンポーネント

import React, { Component } from 'react'; 

import { connect } from 'react-redux'; 

import { fetchHead } from '../actions'; 

class HeadNews extends Component { 

    componentDidMount() { 

    this.props.fetchHead(); 

    console.log(this.props.heads); 
    } 

    render() { 

    return <div>Hello</div>; 

    } 

} 

function mapStateToProps(state) { 

    return { heads: state.heads }; 

} 

export default connect(mapStateToProps, { fetchHead })(HeadNews); 
+0

あなたがネットワーク呼び出しの非同期性を欠けている、API呼び出しは非同期になり、それが同期してデータを返しませんので、あなたは 'Reduxの-thunk'のようないくつかのミドルウェアを含める必要があり、チェックこれらの答え:[Reduxで非同期フロー用のミドルウェアが必要なのはなぜですか?](https://stackoverflow.com/questions/34570758/why-do-we-need-middleware-for-async-flow-in-redux) [非同期呼び出しの応答を返すにはどうすればいいですか?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –

+0

私は考えています。 - それは解決するだろう! – RaMsIs

答えて

0

あなたが減速にdefferedオブジェクトを渡しているとされていないデータは、Ajaxリクエストから返されました。私はあなたがredux-thunkmiddlewareを使用しているかどうかを知りませんが、代わりにアクションのようなプレーンなオブジェクトの機能を返すアクションをディスパッチするためにする必要があります

axios.get(url) 
     .then(function (response) { 
     return { 
      type: FETCH_HEAD, 
      payload: response 
     } 
     }) 
     .catch(function (error) { 
     console.log(error); 
     }); 

EDIT

あなたは.thenを使用する必要がありますredux-thunkを使用する必要があります。

+0

私はそれがOPの問題を解決するとは思わない、彼は 'サンクのようないくつかのミドルウェアが必要です。 –

+0

ありがとう、ええ、私は答えがOPの_redux-thunk_を使用しているかどうか、彼は(シリアル化することができます)アクションではないプレーンオブジェクトを返す必要がありますし、それは自分自身を約束していません。 –

0

だけが、funcnctionレンダリング下にconsole.log:

componentDidMount(){

this.props.fetchHead(); 

}

(レンダリング){

はconsole.log(this.props.heads );

return <div>Hello</div>; 

}

関連する問題