Window.location.reload() in react-native

自闭症网瘾萝莉.ら 提交于 2021-02-11 16:45:47

问题


I often use window.location.reload on my React Web project.

window.location.reload();

Is there any similar way to reload page(component) in react-native?


回答1:


The thing that you mention is a browser feature. React Native uses native capabilities to render your app, so there are no browser features like window.location.reload()

So I am not sure what is your particular use-case for this. I guess it is needed to reload the current screen, not the full app.

In this case, you should use a react-way to re-render your screens. In React the views are re-rendered when the props or state changes. So if you want to trigger a full reload, you need to have some internal state that will trigger a reload. For example, you can use key property and a container with an internal state that toggles this key. But I would consider it a hack. You should really use the react data-driven views You can read more about key prop either in official docs or check out this article from Google: https://kentcdodds.com/blog/understanding-reacts-key-prop/

import React from 'react';
import { View, Text } from 'react-native';

const Container = () => {
  const [key, setKey] = React.useState(0);
  const reload = React.useCallback(() => setKey((prevKey) => prevKey + 1), []);
  return <Child reload={reload} key={key} />;
}

const Child = ({ reload }) => {
  const getRandomId = () => parseInt(Math.random() * 100, 10);
  // We use useRef to showcase that the view is fully re-rendered. Use ref is initialized once per lifecycle of the React component
  const id = React.useRef(getRandomId());
  return (
    <View>
      <Text>My random id is {id}</Text>
      <Button onPress={reload} />
    </View>
  )
}



回答2:


@Coding is Life

import { NavigationEvents } from 'react-navigation';

<NavigationEvents onWillFocus={() => this.goBackReload()}/>

this the way to reload the page. ie' when you goback to page you got the call back method. using this method clear all state value and refresh the page. Another way is refresh control using to reload the app.

<ScrollView  refreshControl={
                        <RefreshControl
                            refreshing={this.state.refreshing}
                            onRefresh={this._onRefresh}
                        />
                    }>
</ScrollView>

When you scroll down the screen onRefresh method trigger.



来源:https://stackoverflow.com/questions/62533860/window-location-reload-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!