React Native返回刷新页面(this.props.navigation.goBack())

this.props.navigation.navigate('NewScreen')到一个新页面之后,通过this.props.navigation.goBack()返回时不会走生命周期方法,所以无法在生命周期方法中进行刷新页面。有如下两种方法进行页面刷新。

  • 通过传递一个callback函数作为参数,在goBack前或后调用callback方法。
  • 通过在goBack前或后发送通知。是通过EventEmitter实现事件机制,实现简单的观察者模式,类似于IOS中的Notification。发送端发送通知,接收端接受到通知后,通过状态机来改变渲染。发送端和接受端同时需要引入DeviceEventEmitter组件。

callback函数刷新。

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Button
} from 'react-native';

export default class HomeScreen extends Component {
    constructor(props){
        super(props);
    }
    static navigationOptions = {
        title: '首页',
      };
    _refresh=()=>{
        console.log('refresh')
        alert('刷新哈!')
    }
    render() {
        return (
            
                
                    Welcome to React Native!
                
                

发送通知DeviceEventEmitter刷新。

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Button,
    DeviceEventEmitter,
} from 'react-native';

export default class HomeScreen extends Component {
    constructor(props){
        super(props);
        this.state = ({
            newMessage:'',
            messageCount:0,
        })
    }
    static navigationOptions = {
        title: '首页',
      };
    _refresh=()=>{
        console.log('refresh')
        alert('刷新哈!')
    }
    componentDidMount(){
        this.refreshSubScription = DeviceEventEmitter.addListener('refresh',(message)=>{
            if(message)
            {
                alert('收到通知啦!')
                this.setState({
                    newMessage:message.message,
                    messageCount:message.messageCount,
                })
            }
        })
    }
    componentWillUnmount(){
        this.refreshSubScription.remove();
    }
    render() {
        return (
            
                
                    Welcome to React Native!
                
                

Simulator Screen Shot - iPhone X - 2019-01-03 at 01.55.54.png

Demo地址

你可能感兴趣的:(React Native返回刷新页面(this.props.navigation.goBack()))