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

如何将使用Reselect的mapStateToProps重写为useSelector并解决参数undefined问题

mapStateToProps 配合 Reselect 转 useSelector 正确实现方案

核心改写逻辑

你使用的selectCollection是Reselect的参数化柯里化选择器,特性是先传业务参数(这里是collectionId),返回接收state作为参数的选择器函数,useSelector会自动把全局state作为参数传入接收的函数,刚好匹配这个调用逻辑。

改写步骤

  • 替换导入:删除import { connect } from "react-redux",新增import { useSelector } from "react-redux",同时导入useParams用于获取路由参数:import { useParams } from "react-router-dom"
  • 删除原有mapStateToProps定义,以及外层connect高阶组件的包裹逻辑
  • 组件内部先获取路由参数collectionId
  • 调用useSelector传入参数化后的选择器,获取collection数据

完整可运行代码

import React from "react";
import { useSelector } from "react-redux";
import { useParams } from "react-router-dom";
import CollectionItem from "../../components/CollectionItem/CollectionItem";
import "./CollectionPage.scss";
import { selectCollection } from "../../redux/shop/shop.selectors";

const CollectionPage = () => {
  // 获取路由中配置的collectionId参数
  const { collectionId } = useParams();
  // useSelector自动传入全局state给selectCollection返回的选择器函数
  const collection = useSelector(selectCollection(collectionId));

  console.log(collection);
  return (
    <div className="collection-page">
      <h2>COLLECTION PAGE</h2>
    </div>
  );
};

export default CollectionPage;

常见undefined问题排查

  • 路由参数不匹配:React Router v6要求路由配置的占位符和useParams解构的变量名完全一致,路由需要配置为/xxx/:collectionId才能正确取值
  • 选择器调用错误:不能写成useSelector(state => selectCollection(collectionId)),也不能写成useSelector(state => selectCollection(collectionId, state)),柯里化选择器要先传参数再把返回的函数传给useSelector

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 06:18:03