我从 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/