【问题标题】:Type InferableComponentEnhancerWithProps is missing the following properties from type Component<OwnProps>InferableComponentEnhancerWithProps 类型缺少 Component<OwnProps> 类型的以下属性
【发布时间】:2021-03-10 13:58:32
【问题描述】:

我正在按照 this 教程在 Typescript 上使用 React 和 Redux 构建聊天应用程序,但在导出连接的组件时出现错误:

Type 'InferableComponentEnhancerWithProps<ConnectedState & ConnectedDispatch, OwnProps>' 
is missing the following properties from type 'Component<OwnProps, {}, any>': 
context, setState, forceUpdate, render, and 3 more.

这是教程中的代码。我应该从什么意义上更新它以消除此错误并能够正常使用该组件。

import * as React from 'react'
import * as redux from 'redux'
import { connect } from 'react-redux'

import { Message as MessageModel, UserMessage} from 'rcserver/src/models'
import { ChatState } from '../state'
import { Action } from '../actions'

import { Messages } from './Messages'
import { ChatInput } from './ChatInput'


interface OwnProps {
  socket: WebSocket,
  username: string
}

interface ConnectedState {
  messages: MessageModel[]
}

interface ConnectedDispatch {}
interface OwnProps {}


const mapStateToProps = (state: ChatState, ownProps: OwnProps): ConnectedState => ({
  messages: state.messages
})

const mapDispatchToProps = (dispatch: redux.Dispatch<Action>): ConnectedDispatch => ({})

export class ChatAppComponent extends React.Component<ConnectedState & ConnectedDispatch & OwnProps> {

  sendHandler = (message: string) => {
    const messageObject: MessageModel = {
      name: this.props.username,
      message: message
    }
    this.props.socket.send(JSON.stringify(messageObject))
  }

  render() {
    return (
      <div className="container">
        <h3>React Chat App</h3>
        <Messages username={this.props.username} messages={this.props.messages} />
        <ChatInput onSend={this.sendHandler} />
      </div>
    )
  }

}
 
export const ChatApp: React.Component<OwnProps> = connect(mapStateToProps, mapDispatchToProps)
//This last line is the one triggering the error

【问题讨论】:

    标签: reactjs typescript redux


    【解决方案1】:

    这几乎是正确的,但是您忘记将connect(mapStateToProps, mapDispatchToProps) 应用于您的ChatAppComponent。这应该有效:

    export const ChatApp = connect(mapStateToProps, mapDispatchToProps)(ChatAppComponent)
    

    ChatApp 的类型将被正确推断,因此您不需要类型签名。如果您确实需要签名,则需要React.FunctionComponent&lt;OwnProps&gt;,因为连接的组件不是类。或者,您也可以使用更通用的React.ComponentType&lt;OwnProps&gt;,它适用于类和函数组件。

    【讨论】:

      猜你喜欢
      • 2021-04-20
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-11
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多