在React Native中,是否有重新装载或重新加载整个屏幕的方法?

我正在构建一个计算器,如果我遵循以下步骤:

它仍然不会重置输入字段.当然,我可以编写一个代码来重置屏幕上的每个字段,但是有没有一种通用的方法来刷新屏幕?

例如,使用导航器,如果我只是转到另一个屏幕,然后返回到这个屏幕,数据将从字段中消失,并且再次全部为0.0.如何做到这一点?

这是组件的第一个 node ,所有的东西都在里面

<ScrollView refreshControl={<RefreshControl
refreshing={this.state.refreshing} onRefresh={this.refreshMe.bind(this)} />}
>
.
.
.
.
.
.
</ScrollView>

谢谢

推荐答案

React中经常使用的一种破解方法是更改组件的keyprops ,以强制重新安装视图:

class Thing extends React.Component {
  state = {
    uniqueValue: 1
  }
  forceRemount = () => {
    this.setState(({ uniqueValue }) => ({
      uniqueValue: uniqueValue + 1
    });
  }
  render() {
    return (
      <View key={this.state.uniqueValue}>
        <Button onPress={this.forceRemount} />
      </View>
    )
  }
}

React使用元素关键点跟踪要更新的元素,如果关键点发生更改,React将得出结论,前一个元素不再存在,因此它将被删除并创建"新"元素.

也就是说,只有当要清除的状态存储在子组件树中的有状态组件中(例如,未设置valueprops 的uncontrolled TextInput)时,这才有效.

一个更干净的解决方案是将所有子组件设置为controlled,这样组件的UI就完全是其props 和状态的函数,只需重置组件状态:

const initialState = {
  //...
}

class Thing extends React.Component {
  state = initialState;
  resetState = () => {
    this.setState(initialState);
  }
  render() {
    return (
      <View}>
        <Button onPress={this.resetState} />
      </View>
    )
  }
}

React-native相关问答推荐

expo 使用错误的版本代码创建建筑

将值从一个 js 文件传递​​到 react native 中的另一个 js 文件:react native

如何在堆栈的任何屏幕的后退按钮按下时始终导航到堆栈的初始路径?

错误:HostFunction 中的异常: Malformed calls from JS: field sizes are different. In an Animated View

在向后滑动时执行操作(react-navigation )

找不到变量 atob

React Redux 使用带有连接组件的 HOC

无法访问函数内部的状态

是否可以在 React Native 中隐藏BugReporting extraData?

React-Native Android - 找不到 com.android.tools:common

在 React Native 中仅显示第一行文本

如何解决react-navigation 问题:Animated: `useNativeDriver` is not supported because the native animated module is missing.?

try 添加包时出现错误duplicate entry:com/google/android/gms/internal/zzble.class

react native图像不适用于特定 URL

require() 必须有一个字符串文字参数 React Native

如何在 React 中使用带有钩子的生命周期方法?

react-native fetch() cookie 持久化

如何在自定义组件上使用 onPress?

使用 React Native 运行多个 iOS 模拟器?

React Native:使用百分比时将视图的宽度设置为等于其高度