从Firebase提取数据之前,mapStateToProps状态两次返回“未定义”

时间:2019-04-18 18:28:12

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

组件在安装之前不会从Firebase检索数据。

const mapStateToProps = (state, ownProps) => {
  return {
    products: state.firestore.ordered.products
  };
};

安装后我测试道具时...

componentDidMount() {
    console.log(this.props);
}

this.props.product的值不确定。


如果我用console.log在mapStateToProps()中的状态参数,我会立即得到两个未定义的console.logs,不久后,我收到了想要的实际数组。

const mapStateToProps = (state, ownProps) => {
  const products2 = state.firestore.ordered.products;

  console.log(products2);  //returns 2 console logs of undefined,
  // after a second (after the component mounts) it gives me the data

  return {
    products: state.firestore.ordered.products
  };
};

这是一个问题,原因是我想使用Firebase中的数据渲染组件。

<div className="item-render-space">
          {products
            .filter(
              eachProduct =>
                eachProduct.landingPageCategory.indexOf(this.props.category) >
                -1
            )
            .map(eachProduct => (
              <div className="each-product" key={eachProduct.id}>
                <Link to={"/product/" + eachProduct.id}>
                  <img src={eachProduct.image} alt="#" />
                  <p className="product-price">{eachProduct.price}</p>
                  <p className="product-name">
                    {nameShortener(eachProduct.name)}
                  </p>
                </Link>
              </div>
            ))}
        </div>

我得到一个错误屏幕,因为未定义变量“ products”,因为Firebase的数据在开始渲染时尚未到达组件。

如何解决此问题?!

编辑:这是rootReducer:

const rootReducer = combineReducers({
  firestore: firestoreReducer, //connects to firestore
  live: liveReducer, //used locally for opening bootstrap modals
  products: productsReducer, //previous products store before implementing Firestore
  firebase: firebaseReducer //connects to firebase
});

1 个答案:

答案 0 :(得分:1)

尝试使用conditional rendering来避免尝试在undefined上执行Array.prototype.filter()和Array.prototype.map()。以下内容将检查products是否真实,并且length大于0:

<div className="item-render-space">
  {products && products.length > 0 && products
    .filter(
      eachProduct =>
        eachProduct.landingPageCategory.indexOf(this.props.category) >
        -1
    )
    .map(eachProduct => (
      <div className="each-product" key={eachProduct.id}>
        <Link to={"/product/" + eachProduct.id}>
          <img src={eachProduct.image} alt="#" />
          <p className="product-price">{eachProduct.price}</p>
          <p className="product-name">
            {nameShortener(eachProduct.name)}
          </p>
        </Link>
      </div>
    ))}
</div>

希望有帮助!