I am using create-react-app. And if you observe the following function I made to request data from firebase:
request = (id) => {
firebaseDB.ref(`Majors/${id}`).once('value')
.then((snapshot)=>{
this.setState({
data: snapshot.val()
})
})
}
as seen above I have updated the state with the value in snapshot.val.
now in the same component, I use this.state.data like this
showCourses(){
this.state.data.Courses.map((item,i)=>(
<div key={i}>
asd
</div>
))
}
and it throws back an error saying 'this.state.data.Courses are not defined' because the response(snapshot) is not back with data yet and the state hasn't been updated.
i tried to add a conditional like this:
showCourses(){
if (this.state.data.Courses){
return(this.state.data.Courses.map((item,i)=>(
<div key={i}>
asd
</div>)))
}
}
the error goes away but it does not render!
I assume the question is: What is the mechanism used to catch, update state and rerender component?
The error is because of this
used in request
function, this
is not binded properly with the element. try using function () {}
syntax and then add this immediately after making the function:
request = request.bind(/* your element */);
i hope it helped :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.