【问题标题】:How to infres types with Partial in react-redux如何在 react-redux 中使用 Partial 来增加类型
【发布时间】:2020-10-18 16:27:44
【问题描述】:

想了半天还是看不懂。
代码如下:

const mapState = (state: AppStateType) => ({
  users: getUsers(state),
  pageSize: getPageSize(state),
  totalUsersCount: getTotalUsersCount(state),
  currentPage: getCurrentPage(state),
  isFetching: getIsFetching(state),
  followingInProgress: getFollowingInProgress(state)
})

const mapDispatch = {
  toggleFollowingInProgress,
  requestUsers,
  follow,
  unfollow
}

const connector = connect(mapState, mapDispatch)

type PropsFromRedux = ConnectedProps<Partial<typeof connector>>
...
export default connector(UsersContainer)

编译时,我看到这个错误:

Users.container.tsx(44,16):
Property 'requestUsers' does not exist on type 'never'.  TS2339

看来他写的是this.props

class UsersContainer extends React.Component<PropsType>
{
  componentDidMount() {
    this.props.requestUsers(this.props.currentPage, this.props.pageSize)
  }

requestUsers 被重击:

export const requestUsers = (page: number, pageSize: number) => async (dispatch: any) => {
  dispatch(toggleIsFetching(true))
}

将返回设置为 void 没有任何效果。
请帮助

【问题讨论】:

    标签: reactjs typescript react-redux typescript-typings partial


    【解决方案1】:

    问题出在Partial上,不适合这个任务,代码阅读混乱。

    type mapStateType = {
      users: userType[]
      pageSize: number
      totalUsersCount: number
      currentPage: number
      isFetching: boolean
      followingInProgress: number[]
    }
    
    type mapDispatchType = {
      toggleFollowingInProgress: (isFetching: boolean, userID: number) => void
      requestUsers: (page: number, pageSize: number) => void
      follow: (userID: number) => void
      unfollow: (userID: number) => void
    }
    
    type ownType = {
      onPageChanged?: (page: number) => void
    }
    
    type PropsType = mapStateType & mapDispatchType & ownType
    

    在其上导出 propsType 和应用程序 Partial 会产生错误,其中类型补码未定义。因此,我严格定义了每个组件中的类型,错误就消失了。

    【讨论】:

      猜你喜欢
      • 2022-10-13
      • 2021-07-02
      • 2021-10-27
      • 2019-11-29
      • 2018-10-04
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多