I found a tutorial online regarding on React.js but I saw the way the tutor did where he change the state without setState() function. I am here asking whether it is a good practice.
The constructor:
constructor(props) {
super(props);
this.state = {
uid: uuid.v1(),
name: '',
answers: {
answer1: '',
answer2: '',
answer3: ''
},
isSubmitted: false
};
this.onSubmit = this.onSubmit.bind(this);
this.answerSelected = this.answerSelected.bind(this);
this.questionSubmitted = this.questionSubmitted.bind(this);
}
The way he update the state is:-
answerSelected(event) {
let answers = this.state.answers;
if (event.target.name === 'answer1') {
answers.answer1 = event.target.value;
} else if (event.target.name === 'answer2') {
answers.answer2 = event.target.value;
} else if (event.target.name === 'answer3') {
answers.answer3 = event.target.value;
}
}
From what I know, React should set state by using setState({answers: {answer1: event.target.value}})
. Am I right? What is the better approach?