问题
I am new to react and I need to render and list data fetched from firebase to the html I tried doing this,
const Music = ({ match }) => {
const [title, setTitle] = useState(null)
const [user, setUser] = useState(null)
const [pfp, setPfp] = useState(null)
const { params: { uID } } = match;
useEffect(()=>{ firebase.database().ref("users/"+uID+"/public/songs/").on("value", (snapshot)=>{
var musics = snapshot.val()
Object.values(musics).forEach((value)=>{
//I need to render this title each and create new li
setTitle(<li>{value.title}</li>)
})
})
}, [])
return(
<>
<Nav />
<div id = "profile" className = "main">
<div class = "profile-container">
<div className = "cover-pic">
<img src = "" />
<div className = "pfp">
<img src = {pfp} height = "100" width = "100"/>
</div>
<div className = "User-Name">
<h1>{user}</h1>
</div>
</div>
<div class = "tabsContainer">
<div class = "tabs-holder">
<NavLink to = {"/u/"+uID+"/music"}><button><span>Music</span></button></NavLink>
<button><span>Playlist</span></button>
<button><span>About</span></button>
</div>
</div>
</div>
<div class = "music-content-container">
<div class = "music-box">
<div class = "user-musics">
<ul>
//the title should rendered over here
{title}
</ul>
</div>
</div>
</div>
</div>
<Header />
)
}
回答1:
Don't rendere stuff in useEffect, just use it to add logic and set state:
const Music = ({ match }) => {
const [musics, setMusics] = useState([])
const [user, setUser] = useState(null)
const [pfp, setPfp] = useState(null)
const { params: { uID } } = match;
useEffect(()=>{
firebase.database()
.ref("users/"+uID+"/public/songs/")
.on("value", (snapshot)=>{
var musics = snapshot.val()
//not sure how music obj is , just set it as an array of something
setMusics(musics)
})
}, [])
return(
<>
<Nav />
<div id = "profile" className = "main">
<div class = "profile-container">
<div className = "cover-pic">
<img src = "" />
<div className = "pfp">
<img src = {pfp} height = "100" width = "100"/>
</div>
<div className = "User-Name">
<h1>{user}</h1>
</div>
</div>
<div class = "tabsContainer">
<div class = "tabs-holder">
<NavLink to = {"/u/"+uID+"/music"}><button><span>Music</span></button></NavLink>
<button><span>Playlist</span></button>
<button><span>About</span></button>
</div>
</div>
</div>
{musics &&
<div class = "music-content-container">
<div class = "music-box">
<div class = "user-musics">
<ul>
{musics.map((el,key)=><li>{el.title}</li>) }}
</ul>
</div>
</div>
</div>}
</div>
<Header />
)
}
来源:https://stackoverflow.com/questions/65167643/how-to-create-new-element-and-render-data-each-time-the-data-is-fetched-in-react