如何访问 redux 选择器中的 useParams 值作为 ownProps

How can I access useParams value inside redux selector as ownProps

import { connect } from 'react-redux';.

import { Outlet, useParams } from 'react-router-dom';

import { selectCollection } from '../../redux/shop/Shop-selectors';

const CollectionPage = ({ collection }) => {
  const params = useParams();
  const paramsId = params.collectionId;
  console.log(collection);
  
  return (
    <div className="collection-page">
      <p>THis is the collection page for {paramsId}</p>
      <Outlet />
    </div>
  );
};

//-- If I log the 'paramsId', I get undefined since it's outside the function

const mapStateToProps = (state, ownProps) => ({
// here is where I wanna use the paramsId as ownProps
  collection: selectCollection(ownProps.paramsId)(state),
});
export default connect(mapStateToProps)(CollectionPage);

我认为你可以通过不同的方式实现这一点,但我建议你使用两种方法来使用来自 useParams Hook 的参数并将其与 react redux 混合

1- 创建另一个顶级组件以在其中获取路由器参数并将它们传递给 CollectionPage 组件,因此在 mapStateToProps 中您可以像这样访问这些参数:

const TopLevelCollectionPage = () => {
  const params = useParams();

  <CollectionPage params={params}></CollectionPage>;
};

const CollectionPage = ({ collection }) => {
  return (
    <div className="collection-page">
      <p>THis is the collection page</p>
      <Outlet />
    </div>
  );
};

const mapStateToProps = (state, ownProps) => ({
  collection: selectCollection(ownProps.params.collectionId)(state),
});
export default connect(mapStateToProps)(CollectionPage);

2- 使用 React redux hooks 获取组件内部的状态

const CollectionPage = () => {
  const params = useParams();
  const collection = useSelector((state) =>
    selectCollection(params.collectionId)(state)
  );
  //or
  //const collection = useSelector(selectCollection(params.collectionId));
};