javascript - 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
}
}
解决方案
我认为这是一个简单的mapDispatchToProps
错误:
export default connect(mapStateToProps, **getAnimals**)(Animals)
用。。。来代替:
export default connect(mapStateToProps, mapDispatchToProps)(Animals)
您还可以内联mapStateToProps
和mapDispatchToProps
在connect
函数中:
export default connect(state => ({
animals: state.animals.animals,
animalsAreLoading: state.animals.isLoading
}), { getAnimals })(Animals)
推荐阅读
- java - Hikari 无法创建池连接
- javascript - 从异步类构造函数创建 observable
- java - ISO-8858-1 到 UTF-8 仅在 URL 中,只有无效字符
- java - 葡萄城excel到pdf缩小以适应
- angular - 从 git 克隆后,ionic 5 项目显示空白模板
- reactjs - 无法从后端使用 React.js 设置数据
- excel - VBA Excel在剪切和粘贴后无法编辑文本框中的文本
- gatsby - GatsbyJS : 将调用 Hubspot API 的脚本放在哪里
- android - 用协程替换自定义回调接口?
- c# - 为什么在 DataTable 中应用 RowFilter 时不考虑空值