kutirie
kutirie

Reputation: 641

Rerender current screen after change state

I use react-native-router-flux and for change some state for some screens I do the following:

index.js

  showMenuIcon(value) {
    this.setState({
      viewMenu: value
    });
  }

...
        <Scene
          renderMenuButton={this.showMenuIcon}
          key="menu"
          component={Services}
          hideNavBar={true}
        />
        <Scene
          renderMenuButton={this.showMenuIcon}
          key="profile"
          component={Profile}
          hideNavBar={true}
        />

Menu.js

        <Button
          title="Test button"
          buttonStyle={[styles.button, styles.blue_button]}
          onPress={() => this.props.renderMenuButton(true)}
          textStyle={{ fontSize: 14 }}
        />

and not only the state changes, but also again render current screen. How to fix?

PS: sorry for my english...

Upvotes: 0

Views: 714

Answers (1)

Selmi Karim
Selmi Karim

Reputation: 2235

By default, shouldComponentUpdate returns true. That’s what causes the “update everything all the time” we saw above. However, you can overwrite shouldComponentUpdate to give it more “smarts” if you need the performance boost. Instead of letting React re-render all the time, you can tell React when you don’t want to trigger a re-render.

When React comes to render the component it will run shouldComponentUpdate and see if it returns true (the component should update, a.k.a. re-render) or false (React can skip the re-render this time). So you’ll need to overwrite shouldComponentUpdate to return true or false as needed to tell React when to re-render and when to skip.

example:

  shouldComponentUpdate(nextProps) {
        const differentTitle = this.props.title !== nextProps.title;
        const differentDone = this.props.done !== nextProps.done
        return differentTitle || differentDone;
    }

Upvotes: 1

Related Questions