Can I access other state variables in state?

时间:2017-04-09 23:51:07

标签: reactjs

Is this considered to be an anti-pattern?

  state = {
    a: true,
    b: !this.state.a,
  }

If not, how could I do this, as this.state inside state is undefined?

1 个答案:

答案 0 :(得分:1)

You shouldn't store both a and b in state if b could be derived from a.

Unneeded state is a bad practice - a code smell if you like to name it that way - that can make work with your component classes harder. Try to think about avoiding and refactoring your component classes to not create unneeded state. Always remember about the single source of truth principle - it can make your component classes simpler to write and maintain. Remember that every denormalised state field is a possible vector of easy bugs.

Ref: http://reactkungfu.com/2015/09/common-react-dot-js-mistakes-unneeded-state/