简体   繁体   中英

React & MobX - To use React's state with MobX is anti-pattern?

In most cases, I use observable with observer() in React components instead of React's state.

However, to use React's state with MobX is anti-pattern? For example, is this below anti-pattern?

@observer
class Counter extends React.Component {
  state = {
    count: 0
  };

  render() {
     return <button onClick={this._handleClick}>{count}</button>
  }

  _handleClick = () => {
    this.setState(prev => {count: prev.count + 1});
  };
}

I know it can be replaced with observable but I wonder if it is an anti-pattern.

Or, is it better to use observable than to use React's state in observed components? if so, why?

The question is why do you have observer there since your component isn't using any observables. You won't gain anything here and you can drop it.

And generally, don't worry about anti-patterns much. As long as something works for you, it's totally fine. Don't let others force you into their opinionated patterns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM