[英]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
:这是将道具传递给
UniqueVenueListing
的GigRegister
组件:
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.