首页 > 解决方案 > 刷新和显示更新的数组后如何防止旧数组保持显示

问题描述

现在我正在尝试在页面上显示一些数组值。数组数据包含在 Firebase 的实时数据库中。在上一页添加到数组/在数据库中输入另一个值后,我们将进入显示数组值的显示页面。这是正在发生的事情的屏幕截图:

使用它拥有的唯一值 88 呈现的数组

将 89 添加到数组后(应该只有两个值,88 和 89,所以应该只显示这两个值,而不是重复 88

这是我的 DashBoard.js 代码

import React, { useState, Component } from 'react'
import { Image, Text, TextInput, TouchableOpacity, View } from 'react-native'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import styles from './styles';
import AsyncStorage from '@react-native-community/async-storage';

import { firebase, firebaseConfig, db, getUserDocument, realtime } from '../../firebase/config'
import "firebase/auth";
import "firebase/firestore";
import "firebase/database";
const user = firebase.auth().currentUser;
var data1 = [];


export default class DashBoard extends React.Component {
    constructor(props) {
        super(props);
        this.state =
        {
            bp: '',
            ag: '',
            mp: '',
            intVal: [],
            dash: ''
        };
    }
    componentDidMount() {
        //console.log(data1);
        const keys = []

        const userRef = firebase.database().ref("users");
        const uidRef = firebase.database().ref("users/" + firebase.auth().currentUser.uid);
        const bpRef = firebase.database().ref("users/" + firebase.auth().currentUser.uid + "/" + "BloodPressure")
        const path = bpRef.toString();

        bpRef.push({
            bpMeasure: this.state.bp,
            date: Date.now(),
        })


        bpRef.once('value').then(snapshot => {
            snapshot.forEach(item => {
                var temp = { bp1: item.val().bpMeasure };

                data1.push(Object.values(temp));
                this.setState({ data1 })
                //this.dash = temp; 
                this.setState({ dash: Object.values(temp) });

                this.setState({ intVal: Object.values(temp) })

                return false;
            });

        });
        // DashBoard.navigationOptions = {
        //     headerTitle: 'Dash Board',
        //     headerLeft: null,
        // }; 
    
    }
    render() {
        return (
            <View style={styles.MainContainer}>
                <View style={styles.innerContainer}>
                    <Text style={styles.TextStyle}>Your Blood Pressure Records</Text>
                    {data1.map((d, i) => (
                        <Text key={i} style={styles.TextStyle}>{d}</Text>
                    ))}
                </View>
            </View>

        )
    }
    
}

带有表单的上一页,MoreInfo.js

import React, { useState, Component } from 'react'
import { Image, Text, TextInput, TouchableOpacity, View } from 'react-native'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import styles from './styles';
import AsyncStorage from '@react-native-community/async-storage';

import { firebase, firebaseConfig, db, getUserDocument, realtime } from '../../firebase/config'
import "firebase/auth";
import "firebase/firestore";
import "firebase/database";

const user = firebase.auth().currentUser;
const counts = []
const trial = [];
let current = []
var data1 = [];
//const[dash, setDash] = useState('')


export default class MoreInfo extends React.Component {
    constructor(props) {
        super(props);
        this.state =
        {
            bp: '',
            ag: '',
            mp: '',
            intVal: [],
            dash: ''
        };
    }
    componentDidMount() {
        this.fetchData();
        db.collection("users").doc(firebase.auth().currentUser.uid).update(
            {
                age: this.state.ag
            }
        ),
            db.collection("users").doc(firebase.auth().currentUser.uid).update(
                {
                    monthsPreg: this.state.mp
                });
    }

    updateInfo = () => {
        const keys = []

        const userRef = firebase.database().ref("users");
        const uidRef = firebase.database().ref("users/" + firebase.auth().currentUser.uid);
        const bpRef = firebase.database().ref("users/" + firebase.auth().currentUser.uid + "/" + "BloodPressure")
        const path = bpRef.toString();

        bpRef.push({
            bpMeasure: this.state.bp,
            date: Date.now(),
        })




        db.collection("users").doc(firebase.auth().currentUser.uid).update(
            {
                age: this.state.ag
            }
        ),
            db.collection("users").doc(firebase.auth().currentUser.uid).update(
                {
                    monthsPreg: this.state.mp
                }
            );
    }

    fetchData = async () => {
        const userRef = firebase.database().ref("users");
        const uidRef = firebase.database().ref("users/" + firebase.auth().currentUser.uid);
        const bpRef = firebase.database().ref("users/" + firebase.auth().currentUser.uid + "/" + "BloodPressure");
        bpRef.once('value').then(snapshot => {
            snapshot.forEach(item => {
                var temp = { bp1: item.val().bpMeasure };
                // var temp = item.val();
                data1.push(Object.values(temp));
                //console.log(data1)
                this.setState({ data1 })
                //this.dash = temp; 
                this.setState({ dash: Object.values(temp) });

                this.setState({ intVal: Object.values(temp) })
                //console.log(this.state.dash);
                return false;
            });
            //console.log(data1[0])
            //    console.log(data1);
            //console.log(data1);

        });
    }


    onPress = () => {
        // navigation.navigate('Home', { user })
    }
    onFooterLinkPress = () => {

        this.props.navigation.navigate('Home', { user })
    }
    onLinkPress = () => {
        this.props.navigation.navigate('DashBoard', { user })
    }


    render() {
        return (
            <View style={styles.container}>
                <KeyboardAwareScrollView style={{ flex: 1, width: '100%' }}
                    keyboardShouldPersistTaps="handled"
                    onPress={KeyboardAwareScrollView.dismiss}
                    accessible={false}
                >
                    <Image
                        style={styles.logo}
                        source={require('../../../assets/icon.png')}
                    />
                    <TextInput
                        style={styles.input}
                        placeholderTextColor="#aaaaaa"
                        secureTextEntry
                        placeholder='Blood Pressure'
                        underlineColorAndroid="transparent"
                        autoCapitalize="none"
                        multiline
                        onChangeText={(bp) => this.setState({ bp })}
                        value={`${this.state.bp}`}
                    />
                    <TextInput
                        style={styles.input}
                        placeholderTextColor="#aaaaaa"
                        secureTextEntry
                        placeholder='Months Pregnant'
                        underlineColorAndroid="transparent"
                        autoCapitalize="none"
                        multiline
                        onChangeText={(mp) => this.setState({ mp })}
                        value={`${this.state.mp}`}
                    />
                    <TextInput
                        style={styles.input}
                        placeholderTextColor="#aaaaaa"
                        secureTextEntry
                        placeholder='Age'
                        underlineColorAndroid="transparent"
                        autoCapitalize="none"
                        multiline
                        onChangeText={(ag) => this.setState({ ag })}
                        value={`${this.state.ag}`}
                    />
                    <View style={styles.innerContainer}>
                        <TouchableOpacity
                            style={styles.button}
                            onPress=
                            {
                                //console.log(data1),
                                this.updateInfo
                                //this.getData
                            }
                        >
                            <Text style={styles.buttonTitle}>Submit Data</Text>
                        </TouchableOpacity>
                    </View>
                    <View style={styles.footerView}>
                        <Text onPress={this.onFooterLinkPress} style={styles.footerLink}>Home</Text>
                    </View>
                    {/* <View style={styles.footerView}>
                        {data1.map((d, i) => (
                            <Text key={i}>{d}</Text>
                        ))}
                        {/* <Text style={styles.footerText}>{"Blood Pressure: "}{this.state.data1}</Text> */}
                    {/* </View>  */}
                    <View style={styles.footerView}>
                        <Text onPress={this.onLinkPress} style={styles.footerLink}>Dashboard</Text>
                    </View>

                   
                </KeyboardAwareScrollView>
            </View>
        );
    }
}

控制台响应:

控制台响应截图


Object {
  "bp1": "120",
}
Array []
Object {
  "bp1": "",
}
Array []
Object {
  "bp1": "99",
}
Array []
Object {
  "bp1": "",
}
Array []
Object {
  "bp1": "100",
}
Array []
Object {
  "bp1": "",
}
Array []
Object {
  "bp1": "",
}
Array []

登录后状态

Array [
  "",
]
Object {
  "bp1": "",
}
Array []
Object {
  "ag": "",
  "bp": "",
  "dash": Array [
    "",
  ],
  "data1": Array [
    "",
  ],
  "intVal": Array [
    "",
  ],
  "mp": "",
}

标签: javascriptreactjsfirebasereact-nativefirebase-realtime-database

解决方案


更新所以我发现了问题:

this.setState(prevState => ({ 
                    data1: [...prevState.data1, temp]
                  }))

//(temp: var temp = item.val().bpMeasure; // item is from the snapshot function)
....

render() {
        console.log(this.state.data1)
        return (
            <View style={styles.MainContainer}>
                <View style={styles.innerContainer}>
                    <Text style={styles.TextStyle}>Your Blood Pressure Records</Text>
                    {this.state.data1.map((d, i) => (
                        <Text key={i} style={styles.TextStyle}>{d}</Text>
                    ))}
                </View>
            </View>

        )
    }

通过这样做,我没有重复地将旧值添加到我的数组中,并且还解决了我在仪表板页面上一次又一次地呈现相同数组的问题。


推荐阅读