mapDispatchToProps is not putting my function into

2019-07-29 06:42发布

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!

3条回答
Fickle 薄情
2楼-- · 2019-07-29 07:19

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";

查看更多
叛逆
3楼-- · 2019-07-29 07:07

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';

查看更多
倾城 Initia
4楼-- · 2019-07-29 07:12

Instead of :

export function fetchPosts () {....

Try:

 export default function fetchPosts () {..
查看更多
登录 后发表回答