【问题标题】:Rerender current screen after change state更改状态后重新渲染当前屏幕
【发布时间】:2018-05-23 12:50:18
【问题描述】:

我使用 react-native-router-flux 并为更改某些屏幕的某些状态,我执行以下操作:

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}
        />

菜单.js

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

不仅状态发生变化,还会再次渲染当前屏幕。 如何解决?

PS:对不起我的英语......

【问题讨论】:

    标签: react-native react-native-router-flux


    【解决方案1】:

    默认情况下,shouldComponentUpdate 返回 true。这就是我们在上面看到的“一直更新所有内容”的原因。但是,如果您需要性能提升,您可以覆盖 shouldComponentUpdate 以使其更加“智能”。您可以在不想触发重新渲染时告诉 React,而不是让 React 一直重新渲染。

    当 React 来渲染组件时,它将运行 shouldComponentUpdate 并查看它是否返回 true(组件应该更新,也就是重新渲染)或 false(React 这次可以跳过重新渲染)。所以你需要覆盖 shouldComponentUpdate 以根据需要返回 true 或 false 来告诉 React 何时重新渲染以及何时跳过。

    示例:

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

    【讨论】:

    • 你能和我们分享一下你在世博会的项目吗?
    猜你喜欢
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 2019-06-29
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多