最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using forceUpdate instead of setState in React? - Stack Overflow

programmeradmin0浏览0评论

If I have a react ponent, and I just set its class variables, ie

class MyComponent extends React.Component {

    constructor(props) {
      super(props);
      this.numberElements = 20;
      this.color = 'red';
    }

    render() { 
       ...
    }
}

Can't I just call this.forceUpdate() to issue a re-render (whenever I update my class variables) instead of maintaining a state and calling setState?. Or is it bad to do that, and if so, why?

If I have a react ponent, and I just set its class variables, ie

class MyComponent extends React.Component {

    constructor(props) {
      super(props);
      this.numberElements = 20;
      this.color = 'red';
    }

    render() { 
       ...
    }
}

Can't I just call this.forceUpdate() to issue a re-render (whenever I update my class variables) instead of maintaining a state and calling setState?. Or is it bad to do that, and if so, why?

Share Improve this question edited Jul 12, 2020 at 18:20 norbitrial 15.2k10 gold badges39 silver badges64 bronze badges asked Mar 3, 2018 at 18:19 Shai UIShai UI 52k77 gold badges218 silver badges316 bronze badges 2
  • Yeah it's bad practise, there is a reason why lifecyle events and setState / props are there. If you need to use forceUpdate then it indicates that you are doing something wrong, imho – Icepickle Commented Mar 3, 2018 at 19:15
  • This might throw more light on it stackoverflow./questions/47237556/… – Shubham Khatri Commented Mar 3, 2018 at 19:28
Add a ment  | 

1 Answer 1

Reset to default 4

forceUpdate() is actually useful in scenarios like the one you're describing.

From the docs:

By default, when your ponent’s state or props change, your ponent will re-render. If your render() method depends on some other data, you can tell React that the ponent needs re-rendering by calling forceUpdate().

The caveat, however, is that it will skip shouldComponentUpdate(), so you're not getting the optimization benefit.

Also, using forceUpdate() "bypasses" the proper lifecycle, making your code less straight-forward and possibly harder to understand and maintain.

It is therefore remended to use state and props when possible.

Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render().

发布评论

评论列表(0)

  1. 暂无评论