我正在尝试使用redux存储从API检索一组产品。
为此,我创建了动作和约简器,一个函数mapStateToProps()
和一个函数mapDispatchToProps()
,后者包含一个函数fetchProducts()
,该函数在动作文件中定义,应调用时检索产品列表。
所有这些都是通过以下方式完成的:
这是概述组件,应呈现数据(实际呈现被忽略,因为它不会影响此问题):
import React, {Component} from 'react';
import {connect} from 'react-redux';
import PropTypes from 'prop-types'
import fetchProductsAction from '../actions/ProductFetchingActionFile'
import {bindActionCreators} from 'redux';
export class Overview extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.props.fetchProducts();
}
render() {
return(
<h1>test</h1>
)
}
}
const mapStateToProps = state => ({
error: state.rootReducer.productsReducer.error,
products: state.rootReducer.productsReducer.products,
pending: state.rootReducer.productsReducer.pending,
})
const mapDispatchToProps = dispatch => bindActionCreators({
fetchProducts: fetchProductsAction
}, dispatch)
Overview.propTypes = {
fetchProducts: PropTypes.func
}
export default connect(mapStateToProps, mapDispatchToProps)(Overview);
这是操作文件(ProductFetchingActionFile):
import {
PREFIX,
FETCH_PRODUCTS_PENDING,
FETCH_PRODUCTS_SUCCESS,
FETCH_PRODUCTS_ERROR
} from "./types";
function fetchProductsPending() {
return{
type: FETCH_PRODUCTS_PENDING
}
}
function fetchProductsSuccess(products) {
return{
type: FETCH_PRODUCTS_SUCCESS,
products: products
}
}
function fetchProductsError(error) {
return{
type: FETCH_PRODUCTS_ERROR,
error: error
}
}
function fetchProducts() {
return dispatch => {
dispatch(fetchProductsPending());
return fetch(`localhost:8080/products`)
.then(res => res.json())
.then(res => {
if(res.error) {
throw(res.error);
}
dispatch(fetchProductsSuccess(res));
return res
})
.catch(error => {
dispatch(fetchProductsError(error));
})
}
}
export default fetchProducts
这是化简文件:
import {
FETCH_PRODUCTS_PENDING,
FETCH_PRODUCTS_SUCCESS,
FETCH_PRODUCTS_ERROR
} from "./types"
const initialState = {
pending: false,
products: [],
error: null
}
export function productsReducer(state = initialState, action) {
switch(action.type) {
case FETCH_PRODUCTS_PENDING:
return {
...state,
pending: true
}
case FETCH_PRODUCTS_SUCCESS:
return {
...state,
pending: false,
products: action.products
}
case FETCH_PRODUCTS_ERROR:
return {
...state,
pending: false,
error: action.error
}
default:
return state;
}
}
现在,加载概述组件时出现以下错误:
TypeError: fetchProducts is not a function
。在fetchProducts
函数中调用componentDidMount()
时会引发此错误。
此外,在此调用之前在控制台中打印Overview.props时,它不包含函数fetchProducts
,因此我怀疑它必须与mapDispatchToProps
做一些事情,但是我无法找到问题。
编辑:最好注意,如果在fetchProductsAction
组件的构造函数中打印了导入的Overview
,它将显示正确的功能。但是,它并没有以props
的{{1}}结尾,因此我希望问题在那里。
答案 0 :(得分:0)
尝试
const mapDispatchToProps = dispatch => {
fetchProducts : () => {
dispatch(fethcProducts())
}
}
答案 1 :(得分:0)
您要将操作导入为
import fetchProductsAction from '../actions/ProductFetchingActionFile'
看起来好像没有默认导出。
可能应该是:
import { fetchProductsAction } from '../actions/ProductFetchingActionFile'