react icon indicating copy to clipboard operation
react copied to clipboard

State annotation inside the constructor

Open kavoos opened this issue 7 years ago • 4 comments

##If you have to initial your state inside the constructor, is it also recommended to add second annotation outside the constructor? something like:

class MyComponent extend<IProps, IState> {
    state: IState
    constructor (props: IProps) {
        super(props)
        this.setState({ name: props.name})
    }
}

P.S. Thanks for your awesome guideline ❤️❤️❤️

kavoos avatar Feb 27 '19 14:02 kavoos

Sorry for ADVANCED label, I can't remove it 😔

kavoos avatar Feb 27 '19 14:02 kavoos

Yes, it's a TypeScript syntax thing for you to actually "declare" all of your properties outside of your constructor, and then actually set them inside your constructor. By the way you don't need to use this.setState inside the constructor you can just do this.state = { name: props.name }

ferdaber avatar Feb 27 '19 14:02 ferdaber

Alternatively:

class MyComponent extend React.Component<IProps, IState> {
    state: IState = {
      name: this.props.name
    }
}

paul-sachs avatar Feb 27 '19 15:02 paul-sachs

yea @psachs21 has it best. i just wouldnt even recommend using constructor at all. cheers.

swyxio avatar Mar 06 '19 08:03 swyxio