首页 > 解决方案 > 未捕获的 TypeError:this.props.getData 不是函数

问题描述

无法调用 Redux 提供的组件内部的函数。

这是我的容器组件

export class HomeContainer extends React.Component {
    render() {
        return(
            <Home 
                getData={ this.props.getData }
            />
        )
    }
}

const mapStateToProps = state => {
    return state;
}

const mapDispatchToProps = dispatch => {
    return bindActionCreators({
        getData: getCountriesList.getCountriesByISO
    }, dispatch);
}

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

我正在使用组件内部调用该 redux 函数

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

这是我的行动

export function getCountriesByISOData() {
    return (dispatch) => {
        dispatch(toggleLoading(true));
        return fetch('/api/countries', {
            method: 'GET',
        }).then(res => {
            if(res.status === 200) {
                return res.json().then(res=> {
                    console.log(res)
                    dispatch(toggleLoading(false));
                    dispatch(isSuccess(res));
                })
            } else {
                dispatch(toggleLoading(false));
                dispatch(isError(res.statusText));
            }
        }).catch(error => {
            dispatch(toggleLoading(false));
            dispatch(isError(error));
        })
    }
}

这是我的减速机

let defaultState = {
    isLoading: false,
    data: [],
    error: ''
}

const getCountriesByISOReducer = (state=defaultState, action) => {
    if(action.type === 'COUNTRIES_ISO_TOGGLE_LOADING') {
        return {
            ...state,
            isLoading: action.isLoading
        }
    }
    if(action.type === 'COUNTRIES_ISO_IS_ERROR') {
        return {
            ...state,
            error: action.error
        }
    }
    if(action.type === 'COUNTRIES_ISO_IS_SUCCESS') {
        return {
            ...state,
            data: [...state.data, action.success]
        }
    }
    return state;
}

export default getCountriesByISOReducer;

这是我的根减速器

export default combineReducers({
    globalConfirmedCases: globalConfirmedCasesReducer,
    dailyStatsByDate: getDailyStatsByDateReducer,
    dailyStats: getDailyStatsReducer,
    getCountriesByISO: getCountriesByISOReducer,
    getCountriesStats: getCountriesStatsReducer
});

我在这里做错了什么?在编写减速器和动作并在反应上下文中使用它时是否有任何命名约定?

标签: reactjsredux

解决方案


推荐阅读