【问题标题】:How to prevent old array from staying displayed after refreshing and displaying updated array刷新和显示更新的数组后如何防止旧数组保持显示
【发布时间】:2021-03-25 04:32:55
【问题描述】:

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

The array being rendered with the only value it has, 88

after adding 89 into the array (there should only be two values, 88 and 89, so only those two should be display, not a repeat of 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>
        );
    }
}

控制台响应:

Console response screenshot


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": "",
}

【问题讨论】:

    标签: javascript reactjs firebase react-native firebase-realtime-database


    【解决方案1】:

    更新所以我发现了问题:

    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>
    
            )
        }
    
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-24
      • 1970-01-01
      • 2018-10-10
      • 2020-03-20
      • 2013-02-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多