mapStateToProps映射后props.products为函数而非数组问题求助
问题:Redux映射props时products为函数而非数组的问题
我已经创建了reducer、action creator和mapStateToProps,在mapStateToProps中打印state能得到预期数据,但组件props里的products却是一个函数模板而非数组。尝试调用该函数会返回pending promise还触发无限循环,求解决方法。
Reducer代码
import { FETCH_PRODUCTS } from '../action/types'; const init = []; const productsReducer = (state = init, action) => { switch (action.type) { case FETCH_PRODUCTS: return action.payload; default: return state; } }; export default productsReducer;
Action Creator代码
export const fetchProducts = () => async (dispatch) => { const { data } = await apiData(products); dispatch({ type: FETCH_PRODUCTS, payload: data.categories, }); };
组件代码
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { fetchCategories, fetchProducts } from '../../../redux/action/actionCreators'; import './women.css'; class All extends Component { componentDidMount() { this.props.categories(); this.props.products(); } render() { console.log(this.props.products); return (<div>Hell0</div>); } } const mapStateToProps = (state) => { // console.log(state); return { products: state.products } }; export default connect(mapStateToProps, { categories: fetchCategories, products: fetchProducts, })(All);
当前输出结果
ƒ () { return dispatch(actionCreator(...arguments)); }
预期结果
数组
已尝试操作
调用console.log(this.props.products());,返回pending promise且触发无限循环
解决方法
问题核心是mapStateToProps和connect的第二个参数(mapDispatchToProps)使用了相同的key products,导致action creator覆盖了从state映射过来的数组。
具体修改步骤:
- 修改mapDispatchToProps中的action creator名称,避免冲突:
export default connect(mapStateToProps, { categories: fetchCategories, fetchProducts: fetchProducts, // 将原key `products`改为`fetchProducts` })(All);
- 同步修改componentDidMount里的调用:
componentDidMount() { this.props.categories(); this.props.fetchProducts(); // 调用改名后的action creator }
- 此时在render中打印
this.props.products即可得到预期的数组:
render() { console.log(this.props.products); // 现在输出数组 return (<div>Hell0</div>); }
内容的提问来源于stack exchange,提问作者Olamarx
相关产品推荐
相关产品推荐

