首页 文章

减速器未被触发(redux-promise with axios)

提问于
浏览
0

我正在尝试用axios进行api调用并将其结果传递给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 in action,null来自组件中的console.log,并且没有来自reducer的console.log,所以它没有被触发,我没有数据要在我的组件中呈现 . 虽然我发出请求并从服务器获取数据的响应,但它不会转到reducer . (此外,案例FETCH_POSTS工作正常,我可以呈现帖子列表,但不是特定的帖子 . )

“axios”:“^ 0.17.0”“redux-promise”:“^ 0.5.3”

1 回答

  • 0

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

    Connect将绑定的动作创建者作为prop发送给组件

相关问题