问题
I am using React with Redux and following a tutorial, but I cannot for the life of me figure out this error.
Uncaught TypeError: this.props.fetchPosts is not a function
I have a src file with actions/index.js and I have a components/posts_index.js file. As far as I can tell, these are the only two files involved in this error, and I do not believe mapDispatchToProps is actually putting my function in this.props, but I don't know why.
components/posts_index.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import fetchPosts from '../actions/index';
class PostsIndex extends Component {
componentWillMount() {
this.props.fetchPosts();
}
render() {
return(
<div>List of Blog Posts</div>
)
}
}
function mapDispatchToProps (dispatch) {
return bindActionCreators({ fetchPosts }, dispatch);
}
export default connect(null, mapDispatchToProps)(PostsIndex);
actions/index.js
import axios from 'axios';
export const FETCH_POSTS = 'FETCH_POSTS';
const ROOT_URL = 'http://reduxblog.herokuapp.com/api';
const API_KEY = '?key=hn8y9e7yhvjkw9w887';
export function fetchPosts () {
const request = axios.get(`${ROOT_URL}/posts${API_KEY}`);
return {
type: FETCH_POSTS,
payload: request
}
}
Any help is greatly appreciated!
回答1:
Instead of :
export function fetchPosts () {....
Try:
export default function fetchPosts () {..
回答2:
In actions/index.js, change to export default
export default function fetchPosts () {
const request = axios.get(`${ROOT_URL}/posts${API_KEY}`);
return {
type: FETCH_POSTS,
payload: request
}
}
or edit import statement in your components/posts_index.js
import { fetchPosts } from '../actions/index';
回答3:
in index.js change your import from scoped
do this
import PostsIndex from "./Components/posts_index";
instead of this import { PostsIndex } from "./Components/posts_index";
来源:https://stackoverflow.com/questions/42195773/mapdispatchtoprops-is-not-putting-my-function-into-props