super got strikethrough in React

后端 未结 4 710
挽巷
挽巷 2021-01-18 23:52

Code

import React, { Component } from \'react\';
import PropTypes from \'prop-types\';
import axios from \'axios\';
import { connect } from \'react-redux\';         


        
相关标签:
4条回答
  • 2021-01-19 00:36

    It appears on my code as well. I used VSCode version 1.49.0 and when I hover to that strikethrough, in essence it said that:

    The React constructor is marked as deprecated

    and shows me this link: https://reactjs.org/docs/legacy-context.html

    But I'm not sure that has something to do with legacy context. So I searched and found this fresh GitHub Issues discussion, they said it might an issue with the react typings.

    Let's wait for an update from them.

    0 讨论(0)
  • 2021-01-19 00:41

    IllusionMH posted this solution in this GitHub thread. You can add

    /** @param {Record<string, any>} props */
    

    above the constructor function as follows:

    class Example extends React.Component {
        /** @param {Record<string, any>} props */
        constructor(props) {
            super(props);
        
            console.log(props.message);
            console.log(this.props.message);
        }
        // ...
    }
    

    I am not a TypeScript expert so cannot explain exactly why it works, I assume there is a type definition somewhere that is not handling the constructor or super function correctly and the comment overrides it and tells Typescript to allow the super function to override it and accept the props parameter, similar to how !important tells CSS to give a style precedence or //prettier-ignore tells prettier to ignore the next line of code though I am sure someone more knowledgeable than myself can give a more detailed or accurate explanation.

    0 讨论(0)
  • 2021-01-19 00:45

    I think it may has to do with ES 6 syntax for React. Now you don't have to use the constructor nor the super in React.

    For example, you can write

    export default class ExpenseForm extends React.Component {
        state ={
            description:'',
            amount:''
        }
    }
    

    VS Code may detect the unnecessary use of constructor and super that is crossed out.

    0 讨论(0)
  • 2021-01-19 00:50

    It seems it is related to the new update of VS Code: https://code.visualstudio.com/updates/v1_49#_deprecated-tag-support-for-javascript-and-typescript

    To fix the issue, for now, you can change super(props) to super() and it will fix it. It will not affect your codes if you are not using props in the codes inside constructor(), which means it will not affect your code since you have not used props inside constructor.

    0 讨论(0)
提交回复
热议问题