Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
104 views
in Technique[技术] by (71.8m points)

javascript - Returning a component from a map function

I want to create a function that maps throw a firestore collection and return a Component for each document in the collection I have tried to use the code below

  <div className="posts">
          
                {
                  db.collection("posts")
                  .get()
                  .then((snapshot) => {
                    snapshot.docs.map((doc)=>(
                      <PostContect img={doc.data().image}   Admin={doc.data().admin} Date={"January 14, 2019"} CommentsNo={"2"} Title={doc.data().title} Body={doc.data().title}  />
                 
                  ))})}
                
</div>

but this error shows:

Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.ode

question from:https://stackoverflow.com/questions/65942882/returning-a-component-from-a-map-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

JSX is not the place to make Ajax calls. Instead make the call inside componentDidMount/useEffect and set the data received inside state. As soon as state is updated with received data, React will automatically re-render the component and display the expected content. Try something as follows:

const [snapshots, setSnapshots] = useState();
useEffect(()=> {
    db.collection("posts")
     .get()
     .then((snapshot) => {
      setSnapshots(snapshot.docs)            
     }
    )
}, []);

render
<div className="posts">
    {snapshots && snapshots.map((doc)=>(
      <PostContect img={doc.data().image} Admin={doc.data().admin} Date={"January 14, 2019"} CommentsNo={"2"} Title={doc.data().title} Body={doc.data().title}  />
     )
    }            
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...