【问题标题】:Wh does redux reducer return an empty object?为什么 redux reducer 返回一个空对象?
【发布时间】:2018-02-23 21:11:12
【问题描述】:

这是我的代码:

动作创建者

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;
  }

}

Reducer 键,承诺

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);

【问题讨论】:

  • 您缺少网络调用的异步特性,api调用将是异步的,它不会同步返回数据,因此您需要包含一些中间件,如Redux-thunk,检查这些答案:@987654321 @和How do I return the response from an asynchronous call?
  • 我认为 redux-promise 会解决这个问题!

标签: reactjs react-router react-redux


【解决方案1】:

您正在将延迟对象传递给减速器,而不是从 ajax 请求返回的数据。
你应该使用.then

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

编辑
我不知道您是否使用 redux-thunk middleware 但为了调度返回函数而不是像操作应该是普通对象的操作,您需要使用 redux-thunk

【讨论】:

  • 我认为这不会解决 OP 的问题,他需要一些中间件,例如 thunk
  • 谢谢,是的,我编辑了答案,尽管 OP 是否使用 redux-thunk 他必须返回一个普通对象作为操作(可以序列化)和不是自己的承诺。
【解决方案2】:

只是渲染功能下的console.log:

componentDidMount() {

this.props.fetchHead();

}

渲染() {

console.log(this.props.heads);

return <div>Hello</div>;

}

【讨论】:

    猜你喜欢
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 2021-08-10
    • 2018-12-17
    • 2017-03-28
    • 2019-11-25
    相关资源
    最近更新 更多