B
B
bormor2018-05-20 15:06:20
JavaScript
bormor, 2018-05-20 15:06:20

React. Is it necessary to use constructor(){...} to set state based on props?

Found that you can set the state directly, based on props

export default class Task extends Component{
    state ={
        currentText: this.props.text, // вот так
    }
    ...

those. set state based on props without calling constructor.
Is this normal practice?
React does not display any warnings in the console.
But the tutorials that I met insisted that for such tasks it is necessary to use
constructor(props){
     super(props);    
     this.state = {currentText: this.props.currentText};   
 }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2018-05-20
@bormor

class properties experimental syntax.
In this case, the state field is set after ( simple example ) the call to the React.Component constructor , which initializes the dedicated props . So when you define state , props are already defined and available.
If you use transform-class-properties , it is included in stage-0, stage-1, stage-2, then feel free to use it.

M
Moro Zota, 2018-05-20
@morozota

This is experimental syntax.
This is normal practice.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question