我正在尝试使用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”
答案 0 :(得分:0)
您需要在var t1 = 'test1';
var i1 = 2;
function testclass(arg) {
object1 = this;
this._t1 = null;
return object1;
}
testclass.prototype = {
dosth: function () {
console.log('doing');
}
}
而不是this.props.getPost
中使用componentDidMount
。
Connect将绑定的动作创建者作为prop
发送给组件