reactjs - 在从 firebase 获取数据之前,mapStateToProps 状态两次返回“未定义”
问题描述
组件在挂载之前不会从 Firebase 检索数据。
const mapStateToProps = (state, ownProps) => {
return {
products: state.firestore.ordered.products
};
};
当我在安装后测试道具时......
componentDidMount() {
console.log(this.props);
}
this.props.product 的值未定义。
如果我 console.log mapStateToProps() 中的 state 参数,我会立即得到两个未定义的 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
});
解决方案
尝试使用条件渲染来避免尝试执行 Array.prototype.filter() 和 Array.prototype.map() undefined
。以下将检查是否products
真实且 alength
大于 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>
希望这会有所帮助!
推荐阅读
- python - 在默认用户模型的情况下,如何解决 Django “TypeError at /auth/users/create_user() missing 1 required positional argument: 'username'”?
- c++ - 前向声明后,我不能在同一命名空间中使用其他类
- c++ - 以下 c++ 代码在 leetcode 中有效,但在我的 vscode 中无效,为什么?
- laravel - irazasyed/telegram-bot-sdk 中带有参数的 triggerCommand
- android - Spinner 不显示项目。我现在正在制作盘点程序。我从 API 获取数据。我有问题。微调器不显示项目
- fractals - 曼德布罗集,混沌轨迹
- r - 使用 dplyr - R 合并两个 csv 文件以从输出文件中删除重复项
- python - 如何“旋转”交换 matplotlib.pyplot.imshow 轴
- powerbi - 计算列和度量之间有什么区别?
- javascript - 三元运算符中的三元运算符是否可能