简体   繁体   中英

how to loop multiple arrays in react native

I am actually want to iterate a collection in firestore which contains multiple documents, and i want to return the doc that contain field uid equal of my uid.

that's the data in firestore:

const { user } = this.props ;
console.log("getting user data: ", user )

result on console

that's my code:

render() {
   const auth = this.props.auth;
   console.log("getting user id: ", auth.uid);

   const userData = user.map((item)=>(
      (item.uid) = (auth.uid)
        ? <Text color="white" size={28} style={{ paddingBottom: 8 }}>
               { item.displayName } </Text>
        : <Text color="white" size={28} style={{ paddingBottom: 8 }}> Error 
          </Text>
      )
    );
return (

              <Block style={styles.profileTexts}>
                  {userData}
              </Block>
   )
}
const mapStateToProps = ( state ) => {
  console.log("state firebase",state);
  return{
    auth: state.firebase.auth,
    user: state.firestore.ordered.users,
  }
}
const mapDispatchToProps = (dispatch) => {
  return {
    signOut: () => dispatch(signOut()),
  }
}

export default compose(
   connect(mapStateToProps, mapDispatchToProps),
   firestoreConnect([
       { collection: 'users'},
   ]))(Profile)

But i got this error: "TypeError: undefined is not an object (evaluating 'o.map')"

inside your map you are using assignment operator instead of comparison operator.

if you just want to return an item which is same as auth.uid use a filter instead

Create a function which returns the item.uid === auth.uid

  userFn = () => {
      const {user} = this.props;
      const authUser = user.filter(item => {
          return item.uid === auth.uid
      })
     if (authUser.length>1){
         return <Text>{authUser[0].displayName}</Text>
     }
     else return <Text>Error</Text>
  }

then inside return statement

  return (
      <View style={{flex:1,justifyContent:'center'}}>
          {this.userFn()}
      </View>
  );

You use user in render() method, but I don't see where did you get them? I think this can fix the problem.

render() {
   const auth = this.props.auth;
   console.log("getting user id: ", auth.uid);


   const user = this.props.user // <=== add this line
   const userData = user.map((item)=>(
   ...

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