如何访问mapStateToProps
中的match
道具?
import React from "react";
import "./collectionpage.styles.scss";
import { connect } from "react-redux";
import { selectCollection } from "../../redux/shop/shop.selector";
import { useMatch } from "react-router-dom";
import Collectionitem from
"../../components/collection-items/Collectionitem.component";
const CollectionPage = ({ collection }) => {
const match = useMatch();
const { title, items } = collection;
return (
<div className="collection-page">
<h2 className="title">{title}</h2>
<div className="items">
{items.map(item => <Collectionitem key={item.id} item={item}/>)}
</div>
</div>
)
}
mapStatetoProps = (state) => {
return ({
collection: selectCollection(match.params.colletionID)(state)
})
}
export default connect(mapStatetoProps)(CollectionPage);
mapStatetoProps
允许您将所有者道具传递给。因此,您可以将match
传递给组件。在这种情况下是CollectionPage
const ComponentA = () => {
const match = useMatch();
return (<CollectionPage match={match}/>)
}
然后:
const mapStateToProps = (state, ownProps) => {
return {
collection: ownProps.match.params.colletionID
}
}
react-router-dom@5
由于您似乎正在使用react-router-dom@5
,因此您可以使用withRouter
高阶组件(HOC(,该组件可以注入路由道具。我经常将其与connect
HOC结合起来,首先包装并注入路由道具,以便在connect
HOC中可以访问它们。
示例:
import { connect } from "react-redux";
import { selectCollection } from "../../redux/shop/shop.selector";
import { withRouter } from "react-router-dom";
const CollectionPage = ({ collection }) => {
....
}
mapStateToProps = (state, props) => ({
collection: selectCollection(props.match.params.colletionID)(state),
});
export default withRouter(
connect(mapStateToProps)(CollectionPage)
);
由于您也在使用Redux,您可能还会发现compose
函数在这里非常方便,可以在您想要装饰的组件上组成所有HOC。它起到了";unnest";你的所有HOC组件都可能使用
示例:
import { compose } from 'redux';
import { connect } from "react-redux";
import { selectCollection } from "../../redux/shop/shop.selector";
import { withRouter } from "react-router-dom";
const CollectionPage = ({ collection }) => {
....
}
mapStateToProps = (state, props) => ({
collection: selectCollection(props.match.params.colletionID)(state),
});
export default compose(
withRouter,
connect(mapStateToProps),
)(CollectionPage);
react-router-dom@6
如果使用react-router-dom@6
,则需要创建自己的自定义withRouter
替换,因为它已在v6中删除。
示例:
import { useParams, /* other hooks */ } from 'react-router-dom';
const withRouter = WrappedComponent => props => {
const params = useParams();
// etc... other react-router-dom v6 hooks
return (
<WrappedComponent
{...props}
params={params}
// etc...
/>
);
};
import { compose } from 'redux';
import { connect } from "react-redux";
import { selectCollection } from "../../redux/shop/shop.selector";
import { withRouter } from "../path/to/withRouter";
const CollectionPage = ({ collection }) => {
....
}
mapStateToProps = (state, props) => ({
collection: selectCollection(props.params.colletionID)(state),
});
export default compose(
withRouter,
connect(mapStateToProps),
)(CollectionPage);