2017-09-26 67 views
1

我有一個基本的條件呈現問題。 基本上我有這個商店:React,Mobx,Firebase條件呈現

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,所以我現在這樣做:

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上的所有數據,當然它會顯示加載消息。

回答

1

你可以只用一個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> 
); 
} 
+1

感謝的人!明天我會在工作中嘗試! :)一個問題,你正在使用replace來返回一個新的數組嗎?使它不可變? –

+0

@LucaBaxter太好了!我正在使用MobX數組[**替換**](https://mobx.js.org/refguide/array.html)方法來替換數組的內容,並且不覆蓋可觀察數組引用一個普通的數組。微妙的錯誤可以通過這種方式引入。 – Tholle