[英]React, Mobx, Firebase conditional rendering
我有一個基本條件渲染的問題。 基本上我有這家商店:
import { ObservableMap, observable, action, computed } from 'mobx';
import fb from '../firebase';
class ProductStore {
@observable products = [];
constructor() {
fb.products.on('value', (snapshot) => {
this.products = [];
snapshot.forEach((child) => {
this.products.push({
id: child.key,
...child.val()
});
});
});
}
@action addProduct = (product) => {
fb.products.push(product);
}
@action removeProduct = (product) => {
fb.products.child(product.id).set({});
}
@computed get totalProducts() {
return this.products.length;
}
}
const store = new ProductStore();
export default store ;
如果我沒有在 firebase 上存儲任何產品,我正在嘗試呈現一條消息,並且正在加載...消息,如果我從 firebase 獲取數據,那么我現在正在這樣做:
const ProductList = (props) => {
const renderView = () => {
if(props.products.length){
return props.products.map((product,index) => <Product key={index} product={product} removeProduct={props.removeProduct}/>);
}else{
return <p>Loading...</p>
}
}
return (
<div className="product-list">
{console.log(props.products)}
{renderView()}
</div>
)
}
如果我沒有關於 firebase 的任何數據,如何打印消息“未找到產品”? 因為一開始我將可觀察到的產品初始化為數組,然后反應顯示加載消息,然后加載數據,但是如果我刪除 firebase 上的所有數據,它當然會顯示加載消息。
您可以使用isLoading
字段擴展您的ProductStore
:
class ProductStore {
@observable products = [];
@observable isLoading = true;
constructor() {
fb.products.on('value', (snapshot) => {
const products = [];
snapshot.forEach((child) => {
products.push({
id: child.key,
...child.val()
});
});
this.products.replace(products);
this.isLoading = false;
}, (error) => {
this.isLoading = false;
});
}
@action addProduct = (product) => {
fb.products.push(product);
}
@action removeProduct = (product) => {
fb.products.child(product.id).set({});
}
@computed get totalProducts() {
return this.products.length;
}
}
並在您的視圖中將其與products.length
結合使用:
const ProductList = ({ isLoading, products }) => {
let result;
if (isLoading) {
result = <p>Loading...</p>;
} else if (products.length === 0) {
result = <p>Products not found</p>;
} else {
result = products.map((product, index) => <Product key={index} product={product} removeProduct={props.removeProduct}/>);
}
return (
<div className="product-list">
{result}
</div>
);
}
如果您使用 firestore,另一種選擇是 Firestorter 庫: https : //github.com/IjzerenHein/firestorter ,其中包含您可以使用的“isLoading”、“isActive”和“ready”。
您可能不想重新設計來執行此操作,但其他人可能會覺得這很有趣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.