最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Next Js & Typescript - Property setState does not exist on type Example - Stack Overflow

programmeradmin3浏览0评论

Code works fine, but I can't figure out how to remove this error in VSCode. Thanks for help.

import * as React from 'react';

interface State {
  text: string;
}
export default class Example extends React.Component<State> {
 state: State = {
    text: 'SOME TEXT'
}

private handleChange = () => {
    this.setState({text: 'New Text'}); //error: property setState does not exist on type Example
}

public render(){
    return(
        <div>
        <h2 onClick={this.handleChange}>{this.state.text}</h2>
        </div>
    )
 }
}

Code works fine, but I can't figure out how to remove this error in VSCode. Thanks for help.

import * as React from 'react';

interface State {
  text: string;
}
export default class Example extends React.Component<State> {
 state: State = {
    text: 'SOME TEXT'
}

private handleChange = () => {
    this.setState({text: 'New Text'}); //error: property setState does not exist on type Example
}

public render(){
    return(
        <div>
        <h2 onClick={this.handleChange}>{this.state.text}</h2>
        </div>
    )
 }
}
Share Improve this question asked Jun 23, 2018 at 18:01 CountDCountD 551 gold badge1 silver badge7 bronze badges 1
  • 1 So even though it's giving you the error, setstate still works? – Blake Steel Commented Jun 23, 2018 at 18:13
Add a comment  | 

2 Answers 2

Reset to default 11

First off, make sure you have the react type definitions installed:

npm install @types/react @types/react-dom

Secondly, the generic for state goes second, not first. The first one is for props.

export default class Example extends React.Component<{}, State> {

Look at the React type definitions to verify this (go to definition on Component). <P, S> means props, then state.

class Component<P, S> {

I resolved the same issue in VSCode just by changing the version of typescript used => open command palette > "select typescript version" > "use workspace version"

发布评论

评论列表(0)

  1. 暂无评论