【问题标题】:how to loop multiple arrays in react native如何在本机反应中循环多个数组
【发布时间】:2019-11-20 06:04:09
【问题描述】:

我实际上想在包含多个文档的 firestore 中迭代一个集合,并且我想返回包含等于我的 uid 的字段 uid 的文档。

这是firestore中的数据:

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

这是我的代码:

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)

但是我收到了这个错误: "TypeError: undefined is not an object (evalating 'o.map')"

【问题讨论】:

    标签: reactjs firebase react-native google-cloud-firestore


    【解决方案1】:

    在您的地图中,您使用的是赋值运算符而不是比较运算符。

    如果您只想返回与auth.uid 相同的项目,请改用过滤器

    创建一个返回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>
      }
    

    然后在return语句中

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

    【讨论】:

    • mathiew 同样的问题!
    • thnx 用于回复,实际上在 return 语句中我将其更改为 {this.userFn} 因为当我用括号 this.userFn is not a function 时它会呈现错误, 但即使不显示 Error 也会返回 null。当我控制台记录它时,它显示:[Function userFn]
    • 去掉括号后代码是否有效?括号对我有用
    • 是的,代码在没有括号的情况下工作,但是这个函数什么也不返回。
    【解决方案2】:

    你在 render() 方法中使用了user,但我不知道你从哪里得到它们? 我认为这可以解决问题。

    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)=>(
       ...
    

    【讨论】:

    • 实际上,当我添加该行时,它显示了我 undefined
    猜你喜欢
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多