reducer 没有被触发(redux-promise with axios)

reducer isn't triggered (redux-promise with axios)

我正在尝试使用 axios 进行 api 调用并将其结果传递给 reducer。 虽然 action 被触发,但 reducer 没有。我不明白为什么。

这是在安装前应该 api 调用的组件

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

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


class PostShow extends Component {
 constructor(props) {
  super(props);

 }

 componentWillMount() {
  getPost(this.props.params.id);
 }
 

 render() {
  console.log(this.props.activePost);
  return (
   <div>
    <h1> hello from a post</h1>
   </div>
  )
 }
}


const mapStateToProps = (state) => {
 return {
  activePost: state.posts.activePost
 }
};

const mapDispatchToProps = (dispatch) => {
 return bindActionCreators({
  getPost
 }, dispatch);
};

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

这是我的行动

import axios from 'axios';

import { FETCH_POSTS, SEND_POST, FETCH_POST } from './types';

const ROOT_URL = 'http://reduxblog.herokuapp.com/api';
const API_KEY = '?key=qwerty';

export function fetchPosts() {
 const req = axios.get(`${ROOT_URL}/posts${API_KEY}`);

 return {
  type: FETCH_POSTS,
  payload: req
 }
}

export function sendPost(props) {
 const req = axios.post(`${ROOT_URL}/posts${API_KEY}`, props);

 return {
  type: SEND_POST,
  payload: req
 }

}

export function getPost(id) {
 console.log('action triggered');
 const req = axios.get(`${ROOT_URL}/posts/${id}${API_KEY}`);

 return {
  type: FETCH_POST,
  payload: req
 }
}

这是我的减速器

import { FETCH_POSTS, FETCH_POST } from '../actions/types';

const INITIAL_STATE = {
 allPosts: [],
 activePost: null
};

export default (state = INITIAL_STATE, action) => {
 switch (action.type) {
  case FETCH_POSTS:
   return {
    ...state,
    allPosts: action.payload.data
   };
  case FETCH_POST:
   console.log('reducer triggered');
   return {
   ...state,
   activePost: action.payload.data
  };
  default:
   return state;
 }
}

因此,我看到 'action triggered' 来自 console.log 的作用,null 来自 console.log 的组件,没有 console.log 来自 reducer,所以它是没有触发,我没有数据要在我的组件中呈现。 虽然我发出请求并从服务器获得数据响应,但它不会进入减速器。 (此外,案例 FETCH_POSTS 工作正常,我可以呈现帖子列表,但不是特定的帖子)。

"axios": "^0.17.0" "redux-promise": "^0.5.3"

您需要在 componentDidMount 中使用 this.props.getPost 而不是 getPost

Connect 将绑定的 action creator 作为 prop 发送到组件