在 react-router v6 的 mapStateToProps 中使用 urlParams

Use urlParams in mapStateToProps in react-router v6

我的 mapStateToProps 需要组件 urlParams 到 select redux 存储的一部分,我尝试使用但我不断收到错误:“TypeError:ownProps.useParams 不是函数” my code

如果我对你的 question/code 的理解是正确的,那么你正在尝试使用 collectionId 路由匹配参数作为进入 selectCollection 选择器的键。

react-router-dom v6 中不再有路由属性,因此渲染组件需要使用 React hooks 来访问 navigatelocationmatch/params。您 可以 走创建自定义 withRouter HOC 的路线,以将匹配参数作为 prop 注入,并且 connect HOC 可以访问,但是使用两个完全不需要高阶组件。

我建议在组件中使用钩子。

import { useSelector } from 'react-redux';
import { useParams } from 'react-router-dom';

const CollectionPage = () => {
  const { collectionId } = useParams();
  const collection = useSelector(selectCollection(collectionId));

  return (
    ... JSX ...
  );
};

export default CollectionPage;