You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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映射过来的数组。

具体修改步骤:

  1. 修改mapDispatchToProps中的action creator名称,避免冲突:
export default connect(mapStateToProps,
  {
    categories: fetchCategories,
    fetchProducts: fetchProducts, // 将原key `products`改为`fetchProducts`
  })(All);
  1. 同步修改componentDidMount里的调用:
componentDidMount() {
  this.props.categories();
  this.props.fetchProducts(); // 调用改名后的action creator
}
  1. 此时在render中打印this.props.products即可得到预期的数组:
render() {
  console.log(this.props.products); // 现在输出数组
  return (<div>Hell0</div>);
}

内容的提问来源于stack exchange,提问作者Olamarx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 14:15:41