【发布时间】: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
【问题讨论】:
-
我看到您既在导出默认值,又在进行命名导出。您将其导入为哪个?如果按命名导入,它不会被
connectHOC 包裹,这会使你的 redux 道具未定义。 -
@BrianThompson,我是作为名称导入的,谢谢亲爱的 .. 它已修复 :)
标签: javascript reactjs redux react-redux redux-thunk