connect(mapStateToProps,{function})没有为此this设置功能。props-React / Redux

时间:2019-02-23 18:57:54

标签: reactjs react-redux

我正在尝试按以下方式在潜在客户组件中的componentDidMount上调用我的API:

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

export class Leads extends Component {

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

    render() {
        return (
            <div>
                <h1>Leads List</h1>
            </div>
        )
    }
}

const mapStateToProps = state => ({
    leads: state.leadsReducer.leads
});


export default connect(mapStateToProps, { getLeads })(Leads);

问题在于最后一行connect()函数似乎没有将getLeads设置为this.props的方法。

登录this.props时,我得到一个空的{}

构建并运行该应用程序时,这就是我在控制台中看到的内容:

Uncaught TypeError: this.props.getLeads is not a function
    at Leads.componentDidMount (Leads.js:42)
    at commitLifeCycles (react-dom.development.js:17130)
    at commitAllLifeCycles (react-dom.development.js:18532)
    at HTMLUnknownElement.callCallback (react-dom.development.js:149)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:199)
    at invokeGuardedCallback (react-dom.development.js:256)
    at commitRoot (react-dom.development.js:18744)
    at eval (react-dom.development.js:20214)
    at Object.unstable_runWithPriority (scheduler.development.js:255)
    at completeRoot (react-dom.development.js:20213)

这是我的../ actions / leads.js

import axios from 'axios';
import { GET_LEADS } from './types';


// GET LEADS
export const getLeads = () => (dispatch) => {
    axios
        .get("/api/leads/")
        .then(res => {
            dispatch({
                type: GET_LEADS,
                payload: res.data
            });
        })
        .catch(err =>console.log(err));
};

我知道我在这里错过了一些愚蠢的东西,很高兴知道什么。

1 个答案:

答案 0 :(得分:0)

您不应该导出类,而应该仅导出连接的实例,否则,如果您使用的类没有连接HOC,那么您将不会在redux商店中看到道具

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

class Leads extends Component {

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

    render() {
        return (
            <div>
                <h1>Leads List</h1>
            </div>
        )
    }
}

const mapStateToProps = state => ({
    leads: state.leadsReducer.leads
});


export default connect(mapStateToProps, { getLeads })(Leads);

现在,要使用Leads组件,您将像默认导入一样导入

import Leads from './path/to/Leads';