redux-thunk action returns 一个函数,不执行,所以不取数据

Redux-thunk action returns a function, which is not executed, so data is not fetched

我有一个容器组件,它应该在安装时用项目数据填充 redux 存储,该组件使用请求的 id 正确调用操作。操作 returns 是一个 dispatch 函数,它永远不会执行,因此永远不会检索数据。

我做错了什么?

我的容器组件是这样的:

import { connect } from "react-redux";
import React, { Component } from "react";

import fetchItem from "../actions/itemActions";
import ItemDetails from "../components/ItemDetails";

class ItemDetailsContainer extends Component {
  state = {
    item: null
  };

  componentDidMount() {
    return fetchItem(this.props.match.params.number);
  }

  render() {
    return <ItemDetails {...this.props} />;
  }
}

const mapStateToProps = (state, props) => {
  return {
    item: state.item,
    user_location: state.user_location
  };
};

export default connect(mapStateToProps)(ItemDetailsContainer);

我的动作文件如下所示:

 import * as actions from "../constants/constants";
import fetch from "isomorphic-fetch";

const itemDetailsRequest = id => {
  return {
    type: actions.FETCH_ITEM_REQUEST,
    id,
    receivedAt: Date.now()
  };
};

const itemDetailsSuccess = (id, json) => {
  return {
    type: actions.FETCH_ITEM_SUCCESS,
    items: json.map(child => child),
    receivedAt: Date.now()
  };
};

const itemDetailsFailure = (id, json) => {
  return {
    type: actions.FETCH_ITEM_FAILURE,
    error: json.error,
    receivedAt: Date.now()
  };
};

const fetchItem = id => {
  console.log(`returning dispatch function for item, id: ${id}`);
  return function(dispatch) {
    console.log("fetching Item: " + id);
    dispatch(itemDetailsRequest(id));
    fetch(`item.json?id=${id}`)
      .then(
        response => response.json(),
        error => console.log("AN ERROR OCCURED.", error)
      )
      .then(json => {
        dispatch(itemDetailsSuccess(id, json));
      });
  };
};

export default fetchItem;

您在调用 fetchItem 时忘记使用 dispatch:

componentDidMount() {
  return this.props.dispatch(fetchItem(this.props.match.params.number));
}

或者不想在componentDidMount中直接使用dispatch,可以直接使用mapDispatchToProps:

const mapStateToProps = (state, props) => {
  return {
    item: state.item,
    user_location: state.user_location
  };
};


const mapDispatchToProps = dispatch => {
  return({
    fetchItem: (number) => dispatch(fetchItem(number)),
  })
}

export default connect(mapStateToProps, mapDispatchToProps)(ItemDetailsContainer);

并且在componentDidMount中:

componentDidMount() {
  return this.props.fetchItem(this.props.match.params.number);
}