简体   繁体   中英

How to return JSX from this function React/React-native

I have a function from where I want to return JSX. I´m new to React, I tried this: history is array of objects and I want to return text from it and display it.

renderCard = () => { const db = firebase.firestore();

db.collection("users")
  .doc(firebase.auth().currentUser.uid)
  .collection("userRequestDeposit")
  .get()
  .then(snapshot => {
    let history = snapshot.docs.map(doc => {
      const data = doc.data().request;
      return { ...data };
    });
 

    history.forEach(elem => {
      return (
        <View>
          <Text>{elem.data}</Text>
        </View>
      );
    });
  });

};

So this is a nice case study for how to use React.

You want to fetch this data when the component mounts. When you have the data, you will update the component's state. You can then render the output from that state.

Here is how you could do this with your code:

import {useEffect, useState} from 'react';

const YourComponent = () => {
  const [history, setHistory] = useState([]); // Store your data in this state

  // this useEffect will run only once (when the component mounts). 
  useEffect(() => {
    db.collection('users')
      .doc(firebase.auth().currentUser.uid)
      .collection('userRequestDeposit')
      .get()
      .then(snapshot => setHistory(snapshot.docs.map(doc => ({...doc.data().request}))));
  }, []); // <-- the empty dependency array means it only runs on mount

  // when history is updated, you can map over the array and render the output here
  return history.map(item => (
    <View key={item.id}>
      <Text>{item.data}</Text>
    </View>
  ));
};

or as a class component...

import {Component} from 'react';

class YourComponent extends Component {
  state = {
    history: [],
  };

  componentDidMount() {
    db.collection('users')
      .doc(firebase.auth().currentUser.uid)
      .collection('userRequestDeposit')
      .get()
      .then(snapshot => {
        this.setState({history: snapshot.docs.map(doc => ({...doc.data().request}))});
      });
  }

  render() {
    return history.map(item => (
      <View key={item.id}>
        <Text>{item.data}</Text>
      </View>
    ));
  }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM