代码之家  ›  专栏  ›  技术社区  ›  Raheel Hasan

React Native-重新安装/重置/重新加载屏幕的最佳方式是什么?

  •  13
  • Raheel Hasan  · 技术社区  · 7 年前

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

    我正在构建一个计算器,如果我遵循以下步骤: https://facebook.github.io/react-native/docs/refreshcontrol.html

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

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

    这是组件的第一个节点,所有内容都在其中

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

    谢谢

    3 回复  |  直到 7 年前
        1
  •  23
  •   jevakallio    7 年前

    React中一个常用的技巧是更改 key 组件的道具,以强制重新装载视图:

    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将得出结论,认为以前的元素不再存在,因此将删除它并创建“新”元素。

    也就是说,只有当要清除的状态存储在子组件树中的有状态组件中(例如 uncontrolled TextInput 它没有 value 道具套件)。

    更清洁的解决方案是制作所有子组件 controlled 因此,组件的UI是其道具和状态的纯功能,只需重置组件状态:

    const initialState = {
      //...
    }
    
    class Thing extends React.Component {
      state = initialState;
      resetState = () => {
        this.setState(initialState);
      }
      render() {
        return (
          <View}>
            <Button onPress={this.resetState} />
          </View>
        )
      }
    }
    
        2
  •  0
  •   Dennis Lee    4 年前

    我的解决方案是使用redux让第二个页面刷新全局状态。然后在第一个页面(返回时),使用useffect根据全局状态中元素的更改刷新所需的数据。 从父(第一)页:

    import { useSelector } from 'react-redux';
    const contacts_update = useSelector( state => state.contact.profile)
    
    useEffect(() => {
      loadContacts();
    }, [contacts_update]);
    
        3
  •  0
  •   Pascal Nitcheu    3 年前

    您可以添加 // @refresh reset => https://reactnative.dev/docs/fast-refresh#tips