首页 > 解决方案 > React-Redux TypeError: this.props.getAnimals is not a function

问题描述

When using react, redux and thunk to fetch some data from an API, I am experiencing an error

TypeError: this.props.getAnimals is not a function\

which is triggered by the line

this.props.getAnimals();

Using Redux Tools, we can see that this.props.getAnimals function was successfully executed, showing the actions animals_are_loading, get_animals and animals_are_loading again, and the states are being updated correctly, as is what you will expect to see when this.props.getAnimals() has called the function getAnimals.

Any idea what is happening?

containers/Animals.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getAnimals } from '../../actions';

class Animals extends Component {

    componentDidMount() {
        this.props.getAnimals();
    }

    renderAnimalsList() {
        return ...
    }

    renderLoading() {
        return ...
    }

    render() {
        return (
            <div>
                <h1>Animals</h1>
                { (this.props.animalsAreLoading) ? this.renderLoading() : this.renderAnimalsList() }
            </div>
        )
    }
}

function mapStateToProps(state) {
    return {
        animals: state.animals.animals,
        animalsAreLoading: state.animals.isLoading
    }
}

function mapDispatchToProps(dispatch) {
    return {
        getAnimals
    }
}

export default connect(mapStateToProps, getAnimals)(Animals)

actions/index.js

import axios from 'axios';
import { GET_ANIMALS_SUCCESS, ANIMALS_ARE_LOADING } from './types';

export function getAnimals() {
    return function(dispatch) {
        dispatch(animalsAreLoading(true))    // ACTION SEEN IN REDUX TOOLS
        axios
            .get(`${ROOT_URL}/animals`, {
                headers: {authorization: localStorage.getItem('token')}
            })
            .then(response => {
                console.log(response.data.animals)    // THIS RETURNS DATA!
                // ACTION SEEN IN REDUX TOOLS
                dispatch(getAnimalsSuccess(response.data.animals)) 
                // ACTION SEEN IN REDUX TOOLS
                dispatch(animalsAreLoading(false))
                return response
            })
    }
}

export function animalsAreLoading(bool) {
    return {
        type: ANIMALS_ARE_LOADING,
        payload: bool
    }
}

export function getAnimalsSuccess(animals) {
    return {
        type: GET_ANIMALS_SUCCESS,
        payload: animals
    }
}

标签: javascriptreactjsreduxreact-reduxredux-thunk

解决方案


我认为这是一个简单的mapDispatchToProps错误:

export default connect(mapStateToProps, **getAnimals**)(Animals)

用。。。来代替:

export default connect(mapStateToProps, mapDispatchToProps)(Animals)

您还可以内联mapStateToPropsmapDispatchToPropsconnect函数中:

export default connect(state => ({
  animals: state.animals.animals,
  animalsAreLoading: state.animals.isLoading 
}), { getAnimals })(Animals)

推荐阅读