reactjs - 如何将 URL 参数传递给选择器

标签 reactjs react-hooks react-router-dom reselect mapstatetoprops

我从 useParams 接收一个 url 参数。我想使用 mapStateToProps 将其传递给选择器。

集合.component.jsx

import { useParams } from "react-router-dom";
import { connect } from "react-redux";

import { selectShopCollection } from "../../redux/shop/shop.selectors";

import './collection.styles.scss'

const Collection = ({ collection }) => {
  const { collectionId } = useParams();
  console.log(collection)
  return (
    <div>
      <h1>{collection}</h1>
    </div>
  )
}

const mapStateToProps = (state, ownProps) => ({
  collection: selectShopCollection(ownProps.match.params.collectionId)(state)
})

export default connect(mapStateToProps)(Collection);

shop.selectors.js

import { createSelector } from "reselect"

const selectShop = state => state.shop

export const selectShopCollections = createSelector([selectShop], shop =>
  shop.collections
)

export const selectShopCollection = collectionUrlParam =>
  createSelector([selectShopCollections], collections =>
    collections.find(collection => collection.id === collectionUrlParam)
  )

我想问题是,我无法使用 match 传递参数,因为 React-router-dom v6 没有在 props 中传递它。是否有其他方法将 collectionId 传递给选择器 selectShopCollection

最佳答案

由于Collection是一个函数组件,我建议从react-redux导入useSelector钩子(Hook),这样你就可以传递collectionId 直接匹配参数。它简化了组件 API。 reselect 选择器与 useSelector Hook 配合良好。

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

import { selectShopCollection } from "../../redux/shop/shop.selectors";
import './collection.styles.scss'

const Collection = () => {
  const { collectionId } = useParams();
  const collection = useSelector(selectShopCollection(collectionId));

  console.log(collection);

  return (
    <div>
      <h1>{collection}</h1>
    </div>
  )
};

export default Collection;

关于reactjs - 如何将 URL 参数传递给选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70364891/

相关文章:

reactjs - 当服务器关闭时 React-Apollo 捕获

reactjs - useState 与 useReducer

javascript - 如何在单独的组件中使用 url 参数

javascript - react 路由器: new component only render on existing view

javascript - ES6 - 警告 : setState(…): Cannot update during an existing state transition

javascript - 使 Ant 设计模式可调整大小

css - 使用 Bootstrap 4 将页脚置于所有其他内容下方

reactjs - 使用 ReactDOM createPortal 制作 React-transition-group 动画

reactjs - useState React 钩子(Hook)总是返回初始值

javascript - 如何动态使用react路由