将react-redux useSelector与打字稿一起使用

时间:2019-05-20 14:54:37

标签: reactjs typescript redux react-redux react-hooks

当尝试使用react-redux打字稿的新useSelector钩子(请参见下面的示例)时,该函数不存在错误:

Module '"../../../node_modules/@types/react-redux"' has no exported member 'useSelector'.  TS2305

示例

import * as React from "react"
import { useSelector } from "react-redux"
import { Message } from "./Message"

export const MessageContainer = () => {
  const searchValue = useSelector((state) => state.search)
  return (
    <Message searchValue={searchValue} />
  )
}

使用的版本: “ react-redux”:“ ^ 7.1.0-alpha.5” “ @ types / react-redux”:“ ^ 7.0.9”

1 个答案:

答案 0 :(得分:0)

以下代码摘自redux doc本身有关打字稿的内容
typescript redux offical

interface RootState {
      isOn: boolean
    }

// TS infers type: (state: RootState) => boolean
const selectIsOn = (state: RootState) => state.isOn

// TS infers `isOn` is boolean
const isOn = useSelector(selectIsOn)

如前所述,在添加钩子之前说过,但是如果使用钩子,则最好这样编写Selector