【问题标题】:React Native force component refresh when the app goes to foreground当应用程序进入前台时 React Native 强制组件刷新
【发布时间】:2019-04-04 15:38:18
【问题描述】:

我的应用显示一些文本。当字体大小通过设置 --> 辅助功能 --> 字体大小发生变化时,我需要重新渲染Component

所以基本上这是se序列:

  • 应用已打开(前台)。
  • 用户打开电话设置,使应用程序进入前台(未完全关闭)。
  • 用户通过设置 --> 辅助功能 --> 更改字体大小 字体大小。
  • 用户关闭设置并打开应用程序进入前台 再次。

此时我需要重新加载应用程序,因为需要调整一些 Components

我正在使用react-native-device-info 来获取使用const fontScale = DeviceInfo.getFontScale(); 的字体大小,但它的值在应用程序完全关闭和打开之前不会更新。

有什么想法吗?

【问题讨论】:

    标签: react-native accessibility react-hooks react-native-device-info font-scaling


    【解决方案1】:

    您可以将appstate 设置为nextAppState。它应该会导致组件重新渲染。

    import React, {Component} from 'react';
    import {AppState, Text} from 'react-native';
    
    class AppStateExample extends Component {
      state = {
        appState: AppState.currentState,
      };
    
      componentDidMount() {
        AppState.addEventListener('change', this._handleAppStateChange);
      }
    
      componentWillUnmount() {
        AppState.removeEventListener('change', this._handleAppStateChange);
      }
    
      _handleAppStateChange = (nextAppState) => {
        if (
          this.state.appState.match(/inactive|background/) &&
          nextAppState === 'active'
        ) {
          console.log('App has come to the foreground!');
        }
        this.setState({appState: nextAppState});
      };
    
      render() {
        return <Text>Current state is: {this.state.appState}</Text>;
      }
    }
    

    【讨论】:

    • 感谢您的回答!是否可以使用钩子来实现?我对 React 很陌生,我的项目使用钩子
    • 我没有深入研究钩子,但只需要几分钟的研究就可以使用hooks 将这样一个简单的组件转换为功能组件。我目前使用的是recomposeJS
    • 每当我在 appStateChange 事件处理程序中使用 setState 时,总是会收到错误消息“无法对未安装的组件执行 React 状态更新”。知道为什么吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    相关资源
    最近更新 更多