我提前道歉,我的英语不好。我正在学习一门关于react的课程,我想把这个组件重写成useSelector,但是我做不到,因为其中一个属性肯定是未定义的。谁能给我解释一下怎么做?我也在使用"Reselect“库
代码:
import React from "react";
import { connect } from "react-redux";
import CollectionItem from "../../components/CollectionItem/CollectionItem";
import "./CollectionPage.scss";
import { selectCollection } from "../../redux/shop/shop.selectors";
const CollectionPage = ({ collection }) => {
console.log(collection);
return (
<div className="collection-page">
<h2>COLLECTION PAGE</h2>
</div>
);
};
const mapStateToProps = (state, ownProps) => ({
collection: selectCollection(ownProps.match.params.collectionId)(state),
});
export default connect(mapStateToProps)(CollectionPage);发布于 2021-09-02 19:23:01
参数化选择器在here中有更详细的解释
您的代码可能如下所示:
//method to get all collections
const selectCollections = (state) => state.collections;
//method to create a selector that gets a selection by id
const createSelectCollectionById = (collectionId) =>
createSelector(
[selectCollections], //all collections
(collections) =>
//just guessing the logic to get collection by id
collections.find(({ id }) => id === collectionId)
);
//use react memo to crate a memoized component
const CollectionPage = React.memo(function CollectionPage(
props
) {
//collection id to create dependency for useMemo
const collectionId = props.match.params.collectionId;
//crate selector for this collection id
const selectCollectionById = React.useMemo(
() => createSelectCollectionById(collectionId),
[collectionId]
);
//use the selector to get the collection item
const collection = useSelector(selectCollectionById);
console.log(collection);
return (
<div className="collection-page">
<h2>COLLECTION PAGE</h2>
</div>
);
});https://stackoverflow.com/questions/69035578
复制相似问题