【问题标题】:mapDispatchToProps is not putting my function into propsmapDispatchToProps 没有将我的功能放入道具中
【发布时间】:2017-02-13 02:28:55
【问题描述】:

我正在使用 React 和 Redux 并按照教程进行操作,但我终生无法弄清楚这个错误。

未捕获的类型错误:this.props.fetchPosts 不是函数

我有一个包含 actions/index.js 的 src 文件和一个 components/posts_index.js 文件。据我所知,这是唯一涉及此错误的两个文件,我不相信 mapDispatchToProps 实际上是将我的函数放在 this.props 中,但我不知道为什么。

组件/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
  }
}

非常感谢任何帮助!

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    而不是:

    export function fetchPosts () {....
    

    试试:

     export default function fetchPosts () {..
    

    【讨论】:

    • 做到了!谢谢你。我有点困惑,因为我从 ... 调用了 import { fetchPosts },它不应该找到 fetchPosts 吗?
    • 当你使用默认的函数时,它知道要导入什么,所以不需要括号。
    【解决方案2】:

    在actions/index.js中,改为export default

    export default function fetchPosts () {
      const request = axios.get(`${ROOT_URL}/posts${API_KEY}`);
    
      return {
        type: FETCH_POSTS,
        payload: request
      }
    }
      

    或在您的 components/posts_index.js 中编辑导入语句

    import { fetchPosts } from '../actions/index';

    【讨论】:

      【解决方案3】:

      在 index.js 中更改您的导入范围

      这样做 import PostsIndex from "./Components/posts_index";

      而不是这个import { PostsIndex } from "./Components/posts_index";

      【讨论】:

        猜你喜欢
        • 2019-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-09
        相关资源
        最近更新 更多