[英]Use a prop element of type RouteComponentProps in react redux using Typescript
I have a Component with the following props:我有一个带有以下道具的组件:
interface LocationBoxProps {
location: Location | null
workshift: Workshift
}
The interface cannot extend RouteComponentProps because it already have a location field and to obtain a cleaner interface I would like to create a field of type RouteComponentProps.该接口不能扩展 RouteComponentProps,因为它已经有一个位置字段,为了获得一个更清晰的接口,我想创建一个 RouteComponentProps 类型的字段。 Something like this:
像这样的东西:
interface LocationBoxProps {
location: Location | null
workshift: Workshift
routeProps: RouteComponentProps // <- new field
}
however I don't know how to map this new field (routeProps) in the mapStateToProps method.但是我不知道如何在 mapStateToProps 方法中映射这个新字段(routeProps)。 I treid
我累了
const mapStateToProps = (store: RootState, ownProps: LocationBoxProps) => {
return{
location: store.work.location,
workshift: store.work.workshift,
routeProps: ownProps.routeProps
}
}
but when I try to do this.props.routeProps.history.push('/something') I get the error但是当我尝试做 this.props.routeProps.history.push('/something') 我得到错误
Cannot read property 'history' of undefined
How can I map correctly routeProps in mapStateToProps?如何在 mapStateToProps 中正确映射 routeProps?
I think you're confusing which props are coming from redux and which are coming from react-router-dom.我认为您混淆了哪些 props 来自 redux,哪些来自 react-router-dom。 Mapping
routeProps: ownProps.routeProps
does nothing because you're expecting the props to already be present under the key routeProps
and then assigning them back to the same key.映射
routeProps: ownProps.routeProps
什么都不做,因为你期望 props 已经存在于 key routeProps
,然后将它们分配回同一个 key。
Do you need to use location
from the router, or just the history
?您需要使用路由器的
location
信息,还是仅使用history
? If all you need is the history then get rid of all of this stuff about routeProps
and just access this.props.history.push('/something')
.如果你需要的只是历史,那么摆脱所有关于
routeProps
东西,只需访问this.props.history.push('/something')
。
If you're concerned about naming collisions, you can access the history and location using hooks so that you can name them whatever you want.如果您担心命名冲突,您可以使用钩子访问历史和位置,以便您可以随意命名它们。 The hooks also make things easier for typescript to understand because
Route
injects props in a way that is somewhat hidden.钩子还使打字稿更容易理解,因为
Route
以某种隐藏的方式注入道具。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.