Проблемы с обновлением компонента - PullRequest
0 голосов
/ 29 апреля 2020

У меня есть компонент заголовка, который содержит счетчик уведомлений, который необходимо обновить, когда пользователь прочитает уведомление.
Мой компонент заголовка:

import React, {Component} from 'react';
import {View, Text, StyleSheet, TouchableOpacity} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import AsyncStorage from '@react-native-community/async-storage';

import api from '../Util/api';

export default class Header extends Component {
    constructor(props) {
        super(props);
        this.state = {};
    }

    async componentDidMount() {
        const student_id = await AsyncStorage.getItem('student_id');
        await api.get(`student/${student_id}`).then(async res => {
            const franchise_id = res.data.franchise_id;
            //Req that bring the notifications counter
            await api
                .get(
                    `notifications/get-notifications/${franchise_id}/${student_id}`
                )
                .then(res => {
                    this.setState({
                        count: res.data.count,
                        loading: false,
                    });
                });
        });
    }
    componentDidUpdate(prevState, prevProps) {
        // console.log(prevState.student);
        const student_id = prevState.student;
        if (student_id) {
            api.get(`student/${student_id}`).then(async res => {
                const franchise_id = res.data.franchise_id;
                await api
                    .get(
                        `notifications/get-notifications/${franchise_id}/${student_id}`
                    )
                    .then(res => {
                        if (res.data.count != this.state.count) {
                            this.setState({
                                count: res.data.count,
                            });
                        }
                    });
            });
        }
    }

    handleClick = page => {
        const {navigation} = this.props;
        if (page == 'notification') {
            navigation.navigate('Notification');
        }
    };
    render() {
        const {title} = this.props;
        // console.log(this.props);
        // const title = 'Home';
        return (
            <View style={styles.header}>
                <View style={styles.titleBox}>
                    <Text style={styles.headerTitle}>{title}</Text>
                </View>
                {this.state.count > 0 ? (
                    <TouchableOpacity
                        style={styles.badgeBox}
                        onPress={() => this.handleClick('notification')}>
                        <Icon name="bell" size={20} color="#3c8dbc" />
                        <Text style={styles.badgeRed}>{this.state.count}</Text>
                    </TouchableOpacity>
                ) : null}
            </View>
        );
    }
}

const styles = StyleSheet.create({
    badgeBox: {
        // borderWidth: 1,
        // borderColor: '#000',
        // flex: 1,
        justifyContent: 'flex-end',
        alignItems: 'center',
        flexDirection: 'row',
        height: 80,
        width: 'auto',
        marginTop: 30,
        paddingRight: 15,
    },
    badgeRed: {
        borderRadius: 30,
        backgroundColor: '#dd4b39',
        color: '#ffffff',
        width: 15,
        height: 15,
        fontSize: 10,
        justifyContent: 'center',
        alignItems: 'center',
        textAlign: 'center',
        position: 'absolute',
        top: 25,
        right: 10,
    },
    titleBox: {
        // borderWidth: 1,
        // borderColor: '#000',
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        marginTop: 30,
    },
    header: {
        // borderWidth: 1,
        // borderColor: '#000',
        position: 'absolute',
        width: '100%',
        height: 80,
        backgroundColor: '#fff',
        justifyContent: 'center',
        alignItems: 'center',
        flexDirection: 'row',
        shadowColor: '#000',
        shadowOffset: {
            width: 0,
            height: 1,
        },
        shadowOpacity: 0.22,
        shadowRadius: 2.22,
        elevation: 3,
        zIndex: 1,
    },
    headerTitle: {
        color: '#000',
        textAlign: 'center',
        fontSize: 18,
        fontWeight: 'bold',
        width: '100%',
        marginTop: 10,
        flex: 1,
    },
});

Ну, на всех страницах я могу обновить счетчик, но на домашней странице счетчик не обновляется:
Мой компонент Home:

import React, {Component} from 'react';
import {View, ScrollView, Text, StyleSheet} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';

import api from '../../Util/api';
import Loading from '../../components/Loading';
import Tabbar from '../../components/Tabbar';
import Header from '../../components/Header';

export default class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
            schedules: [],
            loading: true,
            miniLoading: false,
        };
    }

    async componentDidMount() {
        const student_id = await AsyncStorage.getItem('student_id');
        this.setState({loading: true});
        await api.get(`student/${student_id}`).then(res => {
            this.setState({
                student_id: student_id,
                name: res.data.name,
                id: res.data.id,
                email: res.data.email,
                cpf: res.data.cpf,
                photo: res.data.photo,
                franchise_id: res.data.franchise_id,
                profileImage: res.data.profile_image,
                years: res.data.years,
                isBirthdayToday: res.data.isBirthdayToday,
                overdue_monthly_payment: res.data.overdue_monthly_payment,
                presence_day: res.data.presence_day,
                presence_week: res.data.presence_week,
                presence_month: res.data.presence_month,
                schedules: res.data.schedules,
            });
            const franchise_id = res.data.franchise_id;
            api.get(`franchise/${franchise_id}`).then(response => {
                this.setState({
                    franchise: response.data.franchise.social_name,
                    loading: false,
                });
            });
        });
    }

    componentDidUpdate(prevState, prevProps) {
        console.log('home');
        console.log(prevState);
    }

    render() {
        const schedules = this.state.schedules.map((item, i) => {
            const dates = item.schedules_week.map((date, d) => {
                return (
                    <Text key={d}>
                        {date.start_time} - {date.end_time}
                    </Text>
                );
            });
            return (
                <View
                    key={i}
                    style={[styles.frequencyBox, styles.borderTopRadius]}>
                    <View syle={styles.frequencyBoxColOne}>
                        <Text style={styles.frequencyText}>{item.date}</Text>
                    </View>
                    <View syle={styles.scheduleBoxColTwo}>
                        <Text style={styles.frequencyText}>
                            {item.week_day}
                        </Text>
                    </View>
                    <View>{dates}</View>
                </View>
            );
        });
        return (
            <View style={styles.container}>
                {this.state.loading ? <Loading /> : null}
                {this.state.loading ? null : (
                    <Header
                        title="Home"
                        navigation={this.props.navigation}
                        student={this.state.student_id}
                    />
                )}

                <ScrollView
                    style={styles.scrollContainer}
                    contentContainerStyle={styles.contentContainer}>
                    {this.state.isBirthdayToday ? (
                        <View style={styles.birthdayBox}>
                            <Text style={styles.congratulations}>
                                Parabéns, {this.state.name}
                            </Text>
                            <Text style={styles.yearsText}>
                                Pelos seus {this.state.years} anos!
                            </Text>
                        </View>
                    ) : null}
                    <View style={styles.paymentAdvise}>
                        <Text>{this.state.overdue_monthly_payment}</Text>
                    </View>

                    <View style={styles.defaultBox}>
                        <Text style={styles.defaultTitle}>
                            Minha Frequência
                        </Text>
                        <View
                            style={[
                                styles.frequencyBox,
                                styles.borderTopRadius,
                            ]}>
                            <View syle={styles.frequencyBoxColOne}>
                                <Text style={styles.frequencyText}>Hoje</Text>
                            </View>
                            <View syle={styles.frequencyBoxColTwo}>
                                <Text style={styles.frequencyText}>
                                    {this.state.presence_day}
                                </Text>
                            </View>
                        </View>
                        <View style={styles.frequencyBox}>
                            <View syle={styles.frequencyBoxColOne}>
                                <Text style={styles.frequencyText}>Semana</Text>
                            </View>
                            <View syle={styles.frequencyBoxColTwo}>
                                <Text style={styles.frequencyText}>
                                    {this.state.presence_week}
                                </Text>
                            </View>
                        </View>
                        <View
                            style={[
                                styles.frequencyBox,
                                styles.borderBottom,
                                styles.borderBottomRadius,
                            ]}>
                            <View syle={styles.frequencyBoxColOne}>
                                <Text style={styles.frequencyText}>Mês</Text>
                            </View>
                            <View syle={styles.frequencyBoxColTwo}>
                                <Text style={styles.frequencyText}>
                                    {this.state.presence_month}
                                </Text>
                            </View>
                        </View>
                    </View>

                    <View style={[styles.defaultBox, styles.mb15]}>
                        <Text style={styles.defaultTitle}>
                            Minha Agenda Semanal
                        </Text>
                        <View style={styles.defaultBoxRowTitle}>
                            <View style={styles.defaultBoxColTitle}>
                                <Text style={styles.defaultBoxTitle}>Data</Text>
                            </View>
                            <View style={styles.defaultBoxColTitle}>
                                <Text style={styles.defaultBoxTitle}>
                                    Dia da semana
                                </Text>
                            </View>
                            <View style={styles.defaultBoxColTitle}>
                                <Text style={styles.defaultBoxTitle}>
                                    Horário
                                </Text>
                            </View>
                        </View>
                        {schedules}
                    </View>
                </ScrollView>

                <Tabbar navigation={this.props.navigation} />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f4f7fa',
        // marginTop: 5,
        // padding: 5,
    },
    scrollContainer: {
        flexGrow: 1,
        padding: 5,
        marginTop: 80,
        marginBottom: 55,
    },

    birthdayBox: {
        backgroundColor: '#00a65a',
        borderRadius: 3,
        borderWidth: 1,
        borderColor: '#008d4c',
        margin: 5,
        padding: 15,
    },

    congratulations: {
        color: '#fff',
    },

    yearsText: {
        color: '#fff',
        fontSize: 10,
    },

    paymentAdvise: {
        margin: 5,
        padding: 15,
        borderWidth: 1,
        borderColor: '#008d4c',
        borderRadius: 3,
    },

    defaultTitle: {
        marginLeft: 5,
        marginBottom: 5,
    },

    defaultBox: {
        backgroundColor: '#fff',
        borderTopWidth: 3,
        borderColor: '#d2d6de',
        marginTop: 10,
        marginRight: 5,
        marginLeft: 5,
        borderRadius: 3,
        paddingBottom: 5,
    },

    defaultBoxRowTitle: {
        flexDirection: 'row',
        borderBottomWidth: 1,
        borderWidth: 1,
        borderColor: '#f4f4f4',
        marginRight: 5,
        marginLeft: 5,
        padding: 5,
    },

    defaultBoxColTitle: {
        flex: 1,
    },

    defaultBoxTitle: {
        fontWeight: 'bold',
    },

    frequencyBox: {
        marginRight: 5,
        marginLeft: 5,
        marginBottom: 0,
        padding: 10,
        borderWidth: 1,
        borderColor: '#f4f4f4',
        borderTopWidth: 0,
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center',
    },

    borderBottom: {
        borderBottomWidth: 1,
        borderColor: '#f4f4f4',
    },

    borderTopRadius: {
        borderTopLeftRadius: 3,
        borderTopRightRadius: 3,
    },

    borderBottomRadius: {
        borderBottomLeftRadius: 3,
        borderBottomRightRadius: 3,
    },

    frequencyText: {
        marginRight: 15,
        width: 80,
    },

    frequencyBoxColOne: {
        width: 30,
    },

    mb15: {
        marginBottom: 15,
    },
});

Когда пользователь регистрируется, он направляется на домашнюю страницу, но когда я перехожу с другой страницы на домашнюю, обновление не работает.
Маршруты:

import React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';

import Main from './pages/Main';
import Home from './pages/Home';
import User from './pages/User';
import Menu from './pages/Menu';
import Schedule from './pages/Schedule';
import Evaluation from './pages/Evaluation';
import EvaluationView from './pages/Evaluation/EvaluationView';
import Notification from './pages/Notification';

const Stack = createStackNavigator();

function Routes() {
    return (
        <NavigationContainer>
            <Stack.Navigator>
                <Stack.Screen
                    name="Login"
                    component={Main}
                    options={{headerMode: 'none', headerShown: false}}
                />
                <Stack.Screen
                    name="Home"
                    component={Home}
                    options={{headerMode: 'none', headerShown: false}}
                />
                <Stack.Screen
                    name="User"
                    component={User}
                    options={{headerMode: 'none', headerShown: false}}
                />
                <Stack.Screen
                    name="Menu"
                    component={Menu}
                    options={{headerMode: 'none', headerShown: false}}
                />
                <Stack.Screen
                    name="Schedule"
                    component={Schedule}
                    options={{headerMode: 'none', headerShown: false}}
                />
                <Stack.Screen
                    name="Evaluation"
                    component={Evaluation}
                    options={{headerMode: 'none', headerShown: false}}
                />
                <Stack.Screen
                    name="EvaluationView"
                    component={EvaluationView}
                    options={{headerMode: 'none', headerShown: false}}
                />
                <Stack.Screen
                    name="Notification"
                    component={Notification}
                    options={{headerMode: 'none', headerShown: false}}
                />
            </Stack.Navigator>
        </NavigationContainer>
    );
}

export default Routes;
...