Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

How to refresh a cached screen in React Native when navigating back to it

$
0
0

In my React Native project I have one screen that shows a deck of cards and another that contains game instructions and allows you to shuffle the deck, I switch between cards and instructions with a tab navigator and open instruction screens with a stack navigator.

When I am on a specific card and I switch to the instructions and switch back the card I left is still visible when I return to the card screen, which is good. But when I switch to instructions and hit shuffle the card I left is also still visible when I return to the card screen, which is bad as the first card of my new shuffle should have replaced it.

To solve this I tried to force a new render() when I switched back to the card view after shuffle has been called, so in my CardScreen.tsx I have this:

export class CardScreen extends React.Component<NavProps, {}> {  private cardService = new CardService();  private mounted = false;  // A lot of irrelevant stuff happens. readonly focusSubscription = this.props.navigation.addListener('focus', this.focusListener());  focusListener() {    let self = this as CardScreen;    return function(payload: any): void {    let updateState = false;    let cardState = SpecialState.Card;    if (( !self.cardService.active() || !self.context.running ) && ( self.card.id != self.FIRST_CARD_ID )) {      self.card = self.cardService.firstCard();      updateState = true;      self.context.running = true;    }    if ( self.mounted && updateState ) {          self.setState({ cardState: cardState.toString() });    }  }  render(): JSX.Element {     return ( <Text>{this.card.title}</Text><Text>{this.card.text}</Text>);  }}

Tracking through with the debugger, everything here works as expected when the shuffle has been run ( which sets the context.running property to false as the easiest way to convey the data between screens ) the focusListener is triggered, the current card is updated. When I put a breakpoint on render I can see that this.card contains the correct card that was set in the focusListener call.

But the emulator screen still shows the old card.

If I click on the screen anywhere it immediately updates to the correct one, but it is not automatically refreshed. What do I need to do to show the rendered view as soon as render() has been called?


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>