简体   繁体   English

React-Firebase:为什么在我的一个组件中无限调用 console.log?

[英]React-Firebase: Why is a console.log being infinitely called within one of my components?

I'm creating a project in React, with a Firebase backend.我正在 React 中创建一个项目,后端为 Firebase。

I need the details of an authenticated user passed from the GigRegister component to the UniqueVenueListing component, and am passing it via props.我需要从GigRegister组件传递到UniqueVenueListing组件的经过身份验证的用户的详细信息,并通过道具传递它。

In UniqueVenueListing , I'm making a GET request, then filtering through the data looking for a match.UniqueVenueListing中,我发出GET请求,然后过滤数据以查找匹配项。 Strange thing is this - the console.log I have within the axios call is being called infinitely.奇怪的是 - 我在 axios 调用中的 console.log 被无限调用。 Any ideas as to why?关于为什么的任何想法? Is this some sort of error I've made with asynchronous functions?这是我用异步函数犯的某种错误吗?

This is UniqueVenueListing component where the infinite console.log is occuring:这是发生无限 console.log 的UniqueVenueListing组件:

import React, {useState} from 'react'
import axios from 'axios'
import { auth } from 'firebase/app'

const UniqueVenueListing = (props) => {

    const [gig, setGig] = useState({})
    const authUserId = props.userDetails.uid

    axios
    .get("https://us-central1-gig-fort.cloudfunctions.net/api/getGigListings")
    .then(res => {
        console.log(authUserId)    // **this** is the problematic console.log
        const filteredGigs = res.data
        .filter(gig => {
            gig.user = authUserId
        })
        setGig({
            gig: filteredGigs
        })
        console.log(gig)
    })

    return(
        <div>
        
           {/* {
               gig.map(gigItem => {
                    return gigItem
               })
           } */}
        </div>
    )
}

export default UniqueVenueListing

and this is the GigRegister component that passes props to UniqueVenueListing :这是将道具传递给UniqueVenueListingGigRegister组件:

import React from "react";
    import Header from "./Header";
    import TextField from "@material-ui/core/TextField";
    import Button from "@material-ui/core/Button";
    import axios from "axios";
    import * as firebase from 'firebase'
    import { auth } from 'firebase/app'
    import {Link} from 'react-router-dom'
    import UniqueVenueListing from './UniqueVenueListing'


    class GigRegister extends React.Component {
      constructor() {
        super();
        this.state = {
          name: "",
          venue: "",
          time: "",
          date: "",
          genre: "",
          tickets: "",
          price: "",
          userDetails:{}
        };
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.handleClick = this.handleClick.bind(this)
      }

      handleChange(e) {
        this.setState({
          [e.target.name]: e.target.value,
        });
      }
    
      handleClick(){
        console.log('handle click reached')
        auth().signOut().then(() => {
          console.log('Successfully signed out')
        })
        .catch(err => {
          console.log(err)
        })
      }

      componentDidMount(){
        this.authListener()
      }

      authListener(){
        auth().onAuthStateChanged((user)=>{
          if(user){
            console.log(`user signed in as ${user.email}`)
            this.setState({
              userDetails: user
            })
          } else {
            this.setState({
              userDetails: null
            })
            console.log('no user signed in')
          }
        })
      }
  

      handleSubmit(e) {
        let user = auth().currentUser.uid
        console.log(`this is the userid: ${user}`)
        const gigData = {
          name: this.state.name,
          venue: this.state.venue,
          time: this.state.time,
          date: this.state.date,
          genre: this.state.genre,
          tickets: this.state.tickets,
          price: this.state.price,
          user:user
        };
        
        
        auth().currentUser.getIdToken().then(function(token) {
          axios("http://localhost:5000/gig-fort/us-central1/api/createGigListing", {
            method: "POST",
            headers: {
              "content-type": "application/json",
              "Authorization": "Bearer "+token,
            },
            data: gigData,
          })
      })
          .then((res) => {
            console.log(res);
            this.props.history.push('/Homepage')
          })
          .catch((err) => {
            console.error(err);
          });
      }
    
      returnUser(){
       
      }
    
      render() {

        return (
          <div className="gig-register">
            <Header />
            <h1 className="header-gigReg">Register a gig</h1>
            {
              this.state.userDetails ?
              <button onClick = {this.handleClick}>Sign out </button>
              :
              null
            }
            {
              this.state.userDetails ?
              <h2>You are signed in as {this.state.userDetails.email}</h2>
              :
              null
            }
            
            <Link to="/Homepage" style={{ textDecoration: "none" }}>
            <h2>Go to gig listings</h2>
            </Link>
            <UniqueVenueListing userDetails = {this.state.userDetails}/>
            <form onSubmit={this.handleSubmit}>
              <TextField
                placeholder="Event name"
                defaultValue="Event name"
                id="name"
                name="name"
                onChange={this.handleChange}
              />
              <TextField
                placeholder="Time"
                defaultValue="Time"
                type="time"
                label="Enter start time"
                id="time"
                name="time"
                InputLabelProps={{
                  shrink: true,
                }}
                inputProps={{
                  step: 300, // 5 min
                }}
                onChange={this.handleChange}
              />
              <TextField
                id="date"
                label="Select date"
                type="date"
                defaultValue="2017-05-24"
                InputLabelProps={{
                  shrink: true,
                }}
                onChange={(e) => {
                  this.setState({ date: e.target.value });
                }}
              />
              <TextField
                placeholder="Genre"
                defaultValue="Genre"
                id="genre"
                name="genre"
                onChange={this.handleChange}
              />
              <TextField
                placeholder="Tickets"
                defaultValue="Tickets"
                id="tickets"
                name="tickets"
                onChange={this.handleChange}
              />
              <TextField
                placeholder="Price"
                defaultValue="Price"
                id="price"
                name="price"
                onChange={this.handleChange}
              />
              <Button type="submit">Submit</Button>
            </form>
          </div>
        );
      }
    }
    
    export default GigRegister

Yes, Every time your function is being re-rendered, it calls that axios request too, hence infinite requesting, hence infinite console.logging.是的,每次重新呈现 function 时,它也会调用axios请求,因此无限请求,因此无限 console.logging。

Which should be the fix?哪个应该是修复? This one:这个:

useEffect(() => {
  axios
.get("https://us-central1-gig-fort.cloudfunctions.net/api/getGigListings")
.then(res => {
    console.log(authUserId)    // **this** is the problematic console.log
    const filteredGigs = res.data
    .filter(gig => {
        gig.user = authUserId
    })
    setGig({
        gig: filteredGigs
    })
    console.log(gig)
})
}, [])

That way, the useEffect hook acts as the componentDidMount() function in class-based components, it only gets called when the component first mounts.这样, useEffect钩子在基于类的组件中充当componentDidMount() function,它仅在组件首次安装时被调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React-Firebase:为什么页面在第一次加载时失败,但在刷新时加载正确? - React-Firebase: Why does page fail on first load, but then loads properly on refresh? 为什么我的数组没有更新,即使它在我 console.log() 时更新 - Why isn't my array updating even though it updates when I console.log() 如何在 firebase v9 中使用 useCollection react-firebase 钩子 - How to use useCollection react-firebase hook with firebase v9 Firebase Function console.log() output 没有出现在包含文件中 - Firebase Function console.log() output not showing up in include files 为什么在使用 React Router V6 保护路由时,我使用 AWS Amplify 的 React Authentication 组件会被无限渲染 - Why is my React Authentication component using AWS Amplify being rendered infinitely when using React Router V6 to protect routes react-firebase单页站点中的注销按钮未更改为登录按钮 - Logout button not changing to login button in react-firebase single page site 有没有办法使用 firebase 云消息从 firebase-messaging-sw 执行 console.log - Is there a way to do a console.log from the firebase-messaging-sw with firebase cloud messaging Angular Firestore 在 console.log 上重复 output - Angular Firestore duplicates output on console.log 放大 - 在前端处理 console.log - Amplify - handle console.log in frontend 在哪里可以找到 Firebase 控制台上的功能日志? - Where to find the Funtions log on Firebase Console?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM