删除操作后反应本机导航并刷新同一屏幕

react native navigate and refresh same screen after delete operation

我正在使用列表视图。在该列表中,我可以删除任何记录,但删除后我希望列表视图刷新并显示新记录,这意味着我想调用我的 componentDidMount()。我正在使用 navigation.navigate() 但它没有调用 componentDidMount()。下面是我的代码片段供参考。

    import React, { Component } from 'react';
    import { AppRegistry, StyleSheet, Keyboard , TouchableWithoutFeedback ,TextInput, ActivityIndicator, Picker, Switch, ListView,
    Text, View, Alert, Platform, ToastAndroid, TouchableHighlight, Image, Button, TouchableOpacity, ScrollView } from 'react-native';
    import EvilIcon from 'react-native-vector-icons/EvilIcons';
    import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
    import { StackNavigator } from 'react-navigation';
    import { NavigationActions } from 'react-navigation'
    import Toast from 'react-native-simple-toast';

    class manage_timeslots extends Component 
    {
            static navigationOptions = {
            title: 'Manage Timeslots',
        };

        constructor(props) {
            super(props);
            this.state = {
                isLoading: true,
                text: '',
                stat: '',
            }
            this.arrayholder = [];
        }
        componentDidMount() {
            const base64 = require('base-64');
            this._subscribe = this.props.navigation.addListener('didFocus', () => 
            {    console.log("in focus")
                fetch('APIURL'+this.props.navigation.state.params.campaign_id, {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json',
                        "Authorization": "Basic " + base64.encode("demo:QZMWOL")
                    }
                })
                .then((response) => response.json())
                .then((responseJson) => {  console.log("timeslots: "+ JSON.stringify(responseJson));
                    let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
                    this.setState({
                        isLoading: false,
                        data : "data",
                        dataSource: ds.cloneWithRows(responseJson.Time_Slots),
                    }, function () { //console.log("timeslots: " + this.state.dataSource);
                    });
                })
                .catch((error) => {
                    // Alert.alert(error.toString())
                    this.setState({
                        isLoading: false,
                        data: "noDataFound"
                    })
                });
            });
        }

        onDeleteTimeSlot(Timeslot_id) {
            const base64 = require('base-64');
            fetch('APIURL'+Timeslot_id, {
                method: 'DELETE',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    "Authorization": "Basic " + base64.encode("demo:QZMWOL")
                }
            })
            .then((response) => response.json())
            .then((responseJson) => { console.log("response: " + JSON.stringify(responseJson));
                if(responseJson.Message == 'Data has been deleted successfully!')
                { console.log("here");
                    this.props.navigation.navigate('Eighth', { campaign_id: this.props.navigation.state.params.campaign_id, ClientId: this.props.navigation.state.params.ClientId, Ad_name: this.props.navigation.state.params.Ad_name }    );
                }
                else 
                {
                    console.log(responseJson);
                }
            }).catch((error) => {
                console.error(error);
            });
        }
    }

从 onDeleteTimeSlot() 我需要再次调用 componentDidmount() 函数来刷新新记录的数据源。

import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Keyboard , TouchableWithoutFeedback ,TextInput, ActivityIndicator, Picker, Switch, ListView,
Text, View, Alert, Platform, ToastAndroid, TouchableHighlight, Image, Button, TouchableOpacity, ScrollView } from 'react-native';
import EvilIcon from 'react-native-vector-icons/EvilIcons';
import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
import { StackNavigator } from 'react-navigation';
import { NavigationActions } from 'react-navigation'
import Toast from 'react-native-simple-toast';

class manage_timeslots extends Component 
{
        static navigationOptions = {
        title: 'Manage Timeslots',
    };

    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            text: '',
            stat: '',
        }
        this.arrayholder = [];
    }

    componentDidMount() {
       this.getData()
    }

    getData() {
        const base64 = require('base-64');
        this._subscribe = this.props.navigation.addListener('didFocus', () => 
        {    console.log("in focus")
            fetch('APIURL'+this.props.navigation.state.params.campaign_id, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    "Authorization": "Basic " + base64.encode("demo:QZMWOL")
                }
            })
            .then((response) => response.json())
            .then((responseJson) => {  console.log("timeslots: "+ JSON.stringify(responseJson));
                let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
                this.setState({
                    isLoading: false,
                    data : "data",
                    dataSource: ds.cloneWithRows(responseJson.Time_Slots),
                }, function () { //console.log("timeslots: " + this.state.dataSource);
                });
            })
            .catch((error) => {
                // Alert.alert(error.toString())
                this.setState({
                    isLoading: false,
                    data: "noDataFound"
                })
            });
        });
    }

    onDeleteTimeSlot(Timeslot_id) {
        const base64 = require('base-64');
        fetch('APIURL'+Timeslot_id, {
            method: 'DELETE',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                "Authorization": "Basic " + base64.encode("demo:QZMWOL")
            }
        })
        .then((response) => response.json())
        .then((responseJson) => { console.log("response: " + JSON.stringify(responseJson));
            if(responseJson.Message == 'Data has been deleted successfully!')
            { console.log("here");
                this.getData()
            }
            else 
            {
                console.log(responseJson);
            }
        }).catch((error) => {
            console.error(error);
        });
    }
}

我认为你使用了错误的生命周期方法。componentDidMount只会在组件成功挂载时执行。当您更改数据时,组件不会被卸载然后重新安装以反映更改。为此,您需要使用更新生命周期方法,或者您甚至可以强制更新组件。

默认情况下,当您的组件的状态或道具发生变化时,您的组件将重新渲染。如果您的 render() 方法依赖于其他一些数据,您可以通过调用 forceUpdate()

告诉 React 该组件需要重新渲染

component.forceUpdate(callback)

调用 forceUpdate() 将导致在组件上调用 render(),跳过 shouldComponentUpdate()。这将触发子组件的正常生命周期方法,包括每个子组件的 shouldComponentUpdate() 方法。如果标记发生变化,React 仍然只会更新 DOM。