【问题标题】:Error when referencing value: Maximum update depth exceeded引用值时出错:超出最大更新深度
【发布时间】:2021-01-05 10:09:09
【问题描述】:

我在运行代码时遇到此错误。

错误:超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制了嵌套更新的数量以防止无限循环。 这是我的代码

import React, { Component, useState } from 'react';
import {View, StyleSheet,Button,Text, Image,Alert, } from 'react-native';
import { ScrollView, TextInput, ListItem, TouchableOpacity } from 'react-native-gesture-handler';
import firebase from '../database/firebaseDb';
import Index from './list';
import { useNavigation} from '@react-navigation/native';


export default class Profiles extends React.Component{

    static navigationOptions = {  
        title: 'Profile',  
        headerStyle: {  
            backgroundColor: '#f4511e',  
        },  
        //headerTintColor: '#0ff',  
        headerTitleStyle: {  
            fontWeight: 'bold',  
        },  
    };  

   constructor(props){
       super();

       this.state={
           email_user : props.route.params.email_user,
           password_user : props.route.params.password_user,
           id : '',
           name_user: '',
           first_name_user: '',
       }
      }

      dataBase(){
        var userId = firebase.auth().currentUser.uid;

        let shopRef = firebase.database().ref('User/' + userId);
        var id = [];
        var i =0;
        shopRef.on("value",(snapshot) => {
        snapshot.forEach((childSnapshot) => {
            i = i+1;
                id[i] = childSnapshot.val();             
        });
        
        this.setState({
            first_name_user : id[3],
        })
    //   console.log(this.state.first_name_user);
        });
       

        }

    render(){       
          
        return(
            <View>
               
                <View >
                    {/* <Text>Cover photo</Text> */}
                    <Image
                        style={styles.coverStyle}
                        source={require('../images/cover.jpg')}
                    />
                </View>

                <View style={styles.pdpStyle}>
                    {/* <Text>Photo profile</Text> */}
                    <Image
                    style={styles.photoPdpStyle}
                    source={require('../images/femme.jpeg')}
                    />
                </View>

                <View style={styles.nomStyle}>
                    <Text style={styles.textStyle}>{this.state.first_name_user}</Text>
                </View>

                <View style={styles.pubStyle}>
                    <Button
                        title={"Add"}
                        style={styles.btnStyle}
                    />
                    
                    <TextInput
                        placeholder={'Enter your Ads'}
                        style={styles.txtInputStyle}
                    />
                  
                    <Image 
                    style={styles.imgStyle}
                    source={require('../images/photo.png')} 
                    
                    />
                </View>

                <View style={styles.pubAdd}>

                    <View style={styles.AlignPubStyle}>
                        <Image 
                            style={styles.pubImg}
                            source={require('../images/femme.jpeg')}
                        />
                        <Text style={styles.nameTxtStyle}>
                            Your name
                        </Text>

                    </View>
                <Text >
                Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                 Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
                  when an unknown printer took a galley of type and scrambled it to make a type 
                  specimen book. It has survived not only five centuries, but also the leap into 
               electronic typesetting, remaining essentially unchanged.  Ipsum passages, and more
                 
                </Text>

                <View style={styles.AlignPubCommentStyle}>
                        <Image 
                            style={styles.likeImg}
                            source={require('../images/like.png')}
                        />
                       <TextInput
                            style={styles.txtInputComment}
                            placeholder={'Your comment'}
                       />

                       <View >
                        <TouchableOpacity style={styles.appButtonContainer} onPress={
                            this.dataBase()
                        }>
                            <Text style={styles.appButtonText}>
                                Send
                            </Text>
                        </TouchableOpacity>
                    </View>
                    </View>
            </View>
            
         </View>

        );
    }
}
 

我是 react-native 编码的初学者。 我想要的只是获取 first_name_user 的值,但是当我通过 this.state.first_name_user 调用此值时,会出现错误。 我已经看到了相同问题的所有答案,但他们无法解决我的问题。 你能帮帮我吗?

【问题讨论】:

  • 您有componentWillUpdatecomponentDidUpdate 代码吗?或者是你所有的代码,你没有其他代码,就是这样
  • 不相关但一致的缩进对于使代码可读性大有帮助。
  • 放完整的代码,你的问题是无限渲染,可能是无限的setState调用我们找不到你的问题,没有更广泛的图片

标签: javascript react-native


【解决方案1】:

我不是 100% 确定是这样,但这里有一个可能的解释,在您的数据库函数中创建一个侦听器 (on("value",...))。

因此,点击几下后,您就会有大量的侦听器触发 setState,这可能是渲染过多。

你可以试试这样的:

dataBase(){
    var userId = firebase.auth().currentUser.uid;

    let shopRef = firebase.database().ref('User/' + userId);
    var id = [];
    var i =0;
    const updateCallback = ()=> new Promise((resolve) => {
        (snapshot) => {
            snapshot.forEach((childSnapshot) => {
                i = i+1;
                id[i] = childSnapshot.val();             
            });

            this.setState({
                first_name_user : id[3],
            }, resolve())
        }
    })
    shopRef.on("value", updateCallback);
    updateCallback().then(() =>{
        shopRef.off("value", updateCallback);
    })

}

如果有帮助,请告诉我,检查实现,但你明白了

【讨论】:

  • 它什么也没显示。 first_name_user 的值不会出现在屏幕中
  • 是的,我更新了代码,它是 updateCallback().then(() 而不是 updateCallback.then(()
  • 对不起。它没有显示错误,也不再显示任何内容。
猜你喜欢
  • 2020-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-26
  • 1970-01-01
  • 2021-06-30
  • 2020-11-26
  • 1970-01-01
相关资源
最近更新 更多