D
D
d-virt2016-08-10 19:32:37
JavaScript
d-virt, 2016-08-10 19:32:37

How useful is it to change the state in shouldComponentUpdate?

Hello!
Can you please clarify how expedient it is to change the state in shouldComponentUpdate?

shouldComponentUpdate(nextProps, nextState) {
    this.setState({....});
}

Or a task: I have two states in my component (i.e. two variables setState({val1 = '', val2 = ''})). The value of the first state this.state.val1depends on the value of the second state this.state.val2(i.e.
setState({val1 : this.state.val2 == 1 ? true : false})
).
PS I know that it is this.state.val2 == 1identical this.state.val2 == 1 ? true : false, I wrote it specifically for the eyes of the beholder.
Question: Where is it better to change the value of the first state this.state.val1?
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Risent Veber, 2016-08-10
@d-virt

1. Violates the logic of using the framework - which is very bad in itself, can also lead to infinite recursion (you need to look at the source).
2. No need to try to shove all sorts of variables that are used when rendering into the state. Just refactor your code like this: instead of calling directly, call this.state.val1something along the lines of this.getVal1()
what could be done like this:

class MyComp extends React.Component {
   ...
  getVal1() {
    return this.state.val2 == 1;
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question