ReactJS, Calling setState with same parameter

2020-04-01 11:53发布

I have been reading the React docs and came across shouldComponentUpdate(). My understanding is that everytime setState() is called, a re-render of that component will be updated.

My question is that If the value to be updated is the SAME as the current state value, would this trigger a re-render event? or I would have to manually checks for the current value and value to be updated in shouldComponentUpdate()

标签: reactjs
3条回答
冷血范
2楼-- · 2020-04-01 12:32

The official React documentation states:

The default behavior is to re-render on every state change...

https://reactjs.org/docs/react-component.html#shouldcomponentupdate

This means that by default, render() will be executed if any of a component's state or props values changes.

You can override this default behavior using shouldComponentUpdate(). Here's an example that only updates if a state value changes.

shouldComponentUpdate(nextProps, nextState) {
    return this.state.someValue !== nextState.someValue;
}

Note: this example completely ignores props. So, any changes to props will not trigger render().

查看更多
Viruses.
3楼-- · 2020-04-01 12:38

Adding more to @Jyothi's answer regarding implementing shouldComponentUpdate() to skip unnecessary re-renders, in React 15.3 they introduced a new concept PureComponent. From reactjs docs

The difference between them is that React.Component doesn’t implement shouldComponentUpdate(), but React.PureComponent implements it with a shallow prop and state comparison.

This allows to skip unnecessary calls of render in class components by just implementing PureComponent instead of the usual Component. There are a few caveats with PureComponent though, from the docs about React.PureComponent’s shouldComponentUpdate():

... only shallowly compares the objects. If these contain complex data structures, it may produce false-negatives for deeper differences.

... skips prop updates for the whole component subtree. Make sure all the children components are also “pure”.

Usage of PureComponent can in some cases improve performance of your app. Moreover, it enforces you to keep state and props objects as simple as possible or even better, immutable, which might help simplify the app structure and make it cleaner.

查看更多
我只想做你的唯一
4楼-- · 2020-04-01 12:52

I dont know if I understood your question correctly but react only re renders when there is difference between virtual dom and real dom.

And as Jyothi mentioned in his answer that render method will be called irrespective of the value passed in the set state function but rerendering will depend on what this render method returns.

查看更多
登录 后发表回答