2017-09-26 3 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, 그래서 지금하고 있어요 :

나는 firebase에 대한 데이터가 없으면 "products not found"메시지를 어떻게 인쇄 할 수 있습니까? 시작 부분에서 배열에 관찰 가능한 제품을 초기화 한 다음 로딩 메시지를 표시하고 그 후에 데이터로로드합니다. 그런 다음 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

감사 남자! 내일 나는 그것을 직장에서 시험해 볼 것이다! :) 한 질문, 당신은 새로운 배열을 바로 반환하는 대체를 사용하고 있습니까? 그것을 불변으로 만드는가? –

+0

@LucaBaxter 위대한! 배열의 내용을 바꾸기 위해 MobX 배열 [** replace **] (https://mobx.js.org/refguide/array.html) 메서드를 사용하고 있습니다. 관찰 가능 배열 참조를 덮어 쓰지 않습니다. 보통의 배열. 미묘한 버그가 그런 식으로 소개 될 수 있습니다. – Tholle