繁体   English   中英

Firebase 键返回“未定义”(ReactJS)

[英]Firebase key return 'undefined' (ReactJS)

我试图从 firebase 取回密钥并将其传递给组件,但它返回未定义,我不明白为什么..

这是我试图让它工作的组件:

import React, { Component } from 'react';
import ProductItem from './ProductItem';

class ProductList extends Component {
  render() {
    console.log(this.props.productList);
    return (
      <ul className="product-list mt-5">
        {this.props.productList.map(function (item, idx) {
          return <ProductItem key={idx} pid={item.key} {...item} />;
        })}
      </ul>
    );
  }
}

export default ProductList;

在我的<ProductItem>组件中,如果我使用console.log(this.props.pid) ,它会返回未定义。

这是包含this.props.productList的内容: console.log 截图

编辑:这是父组件:

import React, { Component } from 'react';
import ProductList from '../Product/ProductList';
import * as firebase from 'firebase/app';
import 'firebase/analytics';
import 'firebase/database';
import connectToStores from 'alt-utils/lib/connectToStores';
import ProductStore from '../../stores/ProductStore';
import Actions from '../../actions';

const firebaseConfig = {
  xxx
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();

@connectToStores
class Homepage extends Component {
  constructor() {
    super();
    Actions.getProducts();
    Actions.getBrands();
    Actions.getSellers();
  }

  static getStores() {
    return [ProductStore];
  }

  static getPropsFromStores() {
    return ProductStore.getState();
  }

  render() {
    return (
      <>
        <section>
          <section className="container">
            {this.props.products ? <ProductList productList={this.props.products} /> : null}
          </section>
        </section>
      </>
    );
  }
}

export default Homepage;

以下是动作:

import alt from '../alt';
import * as firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
import _ from 'lodash';

class Actions {
  initSession() {
    return (dispatch) => {
      firebase.auth().onAuthStateChanged((firebaseUser) => {
        if (firebaseUser) {
          const user = {
            id: firebaseUser.uid,
            name: firebaseUser.displayName,
            avatar: firebaseUser.photoURL,
          };

          setTimeout(() => dispatch(user));
        } else {
          const user = null;
        }
      });
    };
  }

  login() {
    return (dispatch) => {
      var auth = firebase.auth();
      var provider = new firebase.auth.FacebookAuthProvider();
      auth
        .signInWithPopup(provider)
        .then(function (authData) {
          const user = {
            id: authData.user.uid,
            name: authData.user.displayName,
            avatar: authData.user.photoURL,
          };

          firebase.database().ref().child('users').child(authData.user.uid).set(user);

          console.log(authData);
          dispatch(user);
        })
        .catch(function (error) {
          // An error occurred
          return;
        });
    };
  }

  logout() {
    return (dispatch) => {
      firebase.auth().signOut();
      setTimeout(() => dispatch(null));
    };
  }

  getProducts() {
    return (dispatch) => {
      firebase
        .database()
        .ref('products')
        .on('value', function (snapshot) {
          const products = _.values(snapshot.val());
          dispatch(products);
        });
    };
  }

  addProduct(product) {
    return (dispatch) => {
      firebase.database().ref('products').push(product);
    };
  }

  getBrands() {
    return (dispatch) => {
      firebase
        .database()
        .ref('brands')
        .on('value', function (snapshot) {
          const brands = _.values(snapshot.val());
          dispatch(brands);
        });
    };
  }

  getSellers() {
    return (dispatch) => {
      firebase
        .database()
        .ref('sellers')
        .on('value', function (snapshot) {
          const sellers = _.values(snapshot.val());
          dispatch(sellers);
        });
    };
  }

  addVote(productId, userId) {
    return (dispatch) => {
      var firebaseRef = firebase.database().ref();
      firebaseRef = firebaseRef.child('products').child(productId).child('upvote');

      var vote = 0;
      firebase
        .database()
        .ref()
        .on('value', (snapshop) => {
          vote = snapshop.val();
        });
      firebaseRef.set(vote + 1);
    };
  }
}

export default alt.createActions(Actions);

firebase
  .database()
  .ref('products')
  .on('value', function (snapshot) {
    const products = _.values(snapshot.val());
    dispatch(products);
  });

此代码和其他类似代码是您从实时数据库获取数据的地方。 snapshot object 有关从数据库读取的内容的信息,如果您注销snapshot.key ,它将为您提供您正在寻找的密钥。 但是,目前您对快照所做的唯一事情就是在其上调用.val() 这当然很有用(因为它为您提供了快照中的数据),但它没有给您密钥。

我不完全了解您的 state 的管理方式; 例如,我对alt-utils库一无所知。 因此,我无法就您应该进行哪些更改给出完整的建议。 但以某种形式,您将需要访问此 function 和其他类似文件中的 snapshot.key。 然后,您要么需要发送一个保存这些键的操作; 或者您需要将键与您从.val()获得的数据合并,然后调度合并的数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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