2017-09-14 43 views
-1

这里是我的代码:Wh还原还原器返回空对象吗?

行动的创建者

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调用将是异步的,它不会同步返回数据,所以你需要包括一些中间件像'终极版 - 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

我想REDX -promise将解决这个问题! – RaMsIs

回答

0

你传递一个递延对象减速,而不是将数据从Ajax请求返回。
你应该使用.then

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

编辑
我不知道,如果你正在使用redux-thunkmiddleware但为了派遣,像一个动作返回,而不是一个普通的对象的功能应该是行动,您需要使用redux-thunk

+0

我不认为这会解决OP的问题,他需要一些像“thunk”这样的中间件。 –

+0

谢谢,是的,我编辑了答案,虽然OP是否使用_redux-thunk_或不,他必须返回一个普通的对象作为一个动作(可以序列化),而不是它承诺的自我。 –

0

只需但CONSOLE.LOG渲染funcnction下:

componentDidMount(){

this.props.fetchHead(); 

}

渲染(){

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

return <div>Hello</div>; 

}