【问题标题】:I am getting TypeError: this.props.function is not a function while fetching from an api我收到 TypeError: this.props.function is not a function while fetching from an api
【发布时间】:2020-05-02 17:40:54
【问题描述】:

我正在尝试从 api 获取数据,但出现错误:TypeError: this.props.getPeople 不是函数,而通过代码看起来一切正常,如下所示:

people-component.js

import React, { Component } from 'react';
import './people-component-styles.css';
import { Container, Row, Col, Card } from 'react-bootstrap';
import { connect } from 'react-redux';
import { getPeople } from '../../actions/index'
import 'react-lazy-load-image-component/src/effects/blur.css';
import 'animate.css/animate.min.css';

export class People extends Component {

    componentDidMount() {
        // console.log(this.props);
        this.props.getPeople();
    }

    render() {
        // console.log(this.props);
        return (
            <Row className='main'>
                hello!  
            </Row>
        );
    }
}

const mapStateToProps = state => ({
    people: state.people
})

const mapDispatchToProps = dispatch => ({
    getPeople: () => dispatch(getPeople())
})

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(People);

actions/index.js

export const getPeople = () => {
    console.log("yes");
    return async dispatch => {
        const response = await fetch('https://dma.com.eg/api.php?action=getPeople', {
            method: 'GET'
        })
        const json = await response.json();
        dispatch({ type: "GET_PEOPLE", payload: json });
    }
}

reducers/index.js

const INITIAL_STATE = {
    people: []
}

const rootReducer = (state = INITIAL_STATE, action) => {

    switch (action.type) {
        case "GET_PEOPLE":
            return ({
                ...state,
                people: state.people.concat(action.payload)
            })
        default:
            return state;
    }
};

export default rootReducer

【问题讨论】:

  • 我看到您既在导出默认值,又在进行命名导出。您将其导入为哪个?如果按命名导入,它不会被connect HOC 包裹,这会使你的 redux 道具未定义。
  • @BrianThompson,我是作为名称导入的,谢谢亲爱的 .. 它已修复 :)

标签: javascript reactjs redux react-redux redux-thunk


【解决方案1】:

由于@Brian Thompson,我将People 组件作为名称导入,而它被默认导出,这要归功于@Brian Thompson .. 它已修复。

【讨论】:

    猜你喜欢
    • 2019-03-11
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    • 2022-11-20
    • 2020-11-08
    • 1970-01-01
    相关资源
    最近更新 更多