Ad

React Component Properties "state" And "setState" Are Not Recognized In TypeScript

- 1 answer

I'm trying to reproduce this:ASP.NET Core: CRUD With React.js and Entity Framework Core, on Visual Studio 2019 with IIS Express (with no Node.js). The typescript files are compiled with NuGet Microsoft.Typescript.MsBuild (3.3.3). But the compilation does not run for Typescript files, since properties "state" and "setState" are not recognized (Visual Studio message is "does not exist") although the TypeScript class inheriting from React.Component.

I have tried changing the javascript compilation to Ecma 6/5/2016...

    import React from 'react';

    export class GetUser extends React.Component  {
        constructor(props) {
            super(props);
            this.state = ...

this.state is underlined with red in Visual Studio, and therefore the file is not transpiled

Ad

Answer

The package react is not exposing it's types. It means that typescript does not know which attributes or methods are declared in React.Component.

And because it doesn't know that this.state exists, it shows you an error.

In order to makes the linter knowing React.Component type, install the package @types/react, like :

npm install --save @types/react

Also, I don't do react, but I've found this :

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

Documentation

Ad
source: stackoverflow.com
Ad