使用带有 typescript 的反作用还原useSelector

wnavrhmk  于 2023-02-13  发布在  TypeScript
关注(0)|答案(1)|浏览(121)

当尝试使用react-redux的新useSelector钩子(见下例)时,typescript给出一个错误,即函数不存在:

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-α 5" "@类型/React还原型":"^7.0.9"
pgx2nnw8

pgx2nnw81#

下面的代码取自redux doc本身关于typescript的内容
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)

就像它在后来添加钩子之前所说的那样,但是如果你使用钩子,你最好这样写选择器

相关问题