【问题标题】:I cheated to make redux work, how does this work?我作弊使 redux 工作,这是如何工作的?
【发布时间】:2025-12-03 07:20:04
【问题描述】:

所以我正在学习反应,但我不是 javascript 粉丝,所以我使用的是打字稿。因此,我尝试输入内容,但似乎使用any 总是作弊出路。这是我的容器:

interface UserProfileRouteProps {
  userId: string
}

export function mapStateToProps(state: StoreState, props: RouteComponentProps<UserProfileRouteProps>) {
  let userId: number = parseInt(props.match.params.userId)
  const user = state.users.find(u => u.id === userId)

  return {
    id: userId,
    name: user.name,
    foo: user.foo
  }
}

export function mapDispatchToProps(dispatch: Dispatch<actions.UserProfileActions>, props: RouteComponentProps<UserProfileRouteProps>) {
    let userId: number = parseInt(props.match.params.userId)
  return {
    onFoo: () => dispatch(actions.foo()),
    onDelete: () => dispatch(actions.delete(recipeId))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(UserProfile as any)

这是组件

export interface UserProfileProps{
  id: number
  name: string
  foo: IFoo
  onFoo?: () => void
  onDelete?: () => void  
}

export class UserProfile extends React.Component<UserProfileProps, void>{

现在我希望我的mapStateToPropsmapDispatchToProps 是强类型的,并且返回类型为UserProfileProps,但我不能这样做,因为connect() 抛出了一个错误:

error TS2345: Argument of type 'typeof UserProfile' is not assignable to parameter of type 'ComponentType&lt;UserProfileProps &amp; { onFoo: () =&gt; { type: string; }; onDelete: () =&gt; ...'

所以我在谷歌上搜索后的作弊是去UserProfile as any

这里实际发生了什么?我这样做对吗?我应该有单独的容器道具和组件道具吗?我试图让组件不知道路由。

【问题讨论】:

    标签: reactjs typescript react-redux


    【解决方案1】:

    你可以使用通用形式的连接

    export default connect<{}, {}, UserProfileProps>(
        mapStateToProps,
        mapDispatchToProps
    )(UserProfile);
    

    【讨论】:

    • 这给了我错误error TS2345: Argument of type '(state: StoreState, props: RouteComponentProps&lt;UserProfileRouteProps&gt;) =&gt; { id: number; name: st...' is not assignable to parameter of type 'MapStateToPropsParam&lt;{}, UserProfileProps&gt;'.