2017-12-31 141 views
0

내 Mobx 저장소에 아래의 인출 요청이 : 나는 아래 ReactJS 클래스에서 이것을 사용하고CONSOLE.LOG 인쇄는 reactjs/mobx 프로젝트에서 작동하지 않습니다

getAllLegoParts = action("get all lego",() => { 
this.legoParts = fromPromise(
    fetch("http://localhost:8000/LegoPieces", { 
    method: "GET", 
    cache: "no-store" 
    }).then(response => response.json()) 
); 
}); 
} 

:

을 두 번

  1. CONSOLE.LOG 인쇄 - 정의되지 않은 인쇄 한 경우, 초 :

    class ViewLegos extends Component { 
    constructor(props) { 
    super(props); 
    this.props.store.getAllLegoParts(); 
    } 
    
    render() { 
    console.log(this.props.store.legoParts.value); 
    return (
        <div> 
        <table> 
         <thead> 
         <tr> 
          <th>Piece</th> 
          <th>Type</th> 
         </tr> 
         </thead> 
         <tbody> 
         {this.props.store.legoParts.map(legoPart => (
          <tr key={legoPart.id}> 
          <td>{legoPart.piece}</td> 
          <td>{legoPart.piece}</td> 
          <td>{legoPart.type}</td> 
          </tr> 
         ))} 
         </tbody> 
        </table> 
        </div> 
    ); 
    } 
    } 
    
    export default inject("store")(observer(ViewLegos)); 
    

    그러나 나는이 문제가 그것은 객체 배열을 인쇄합니다 (이것이 내가 원하는 것입니다).

  2. 내가 말하는 오류를 얻을 :

    TypeError: this.props.store.legoParts.map is not a function 
    

감사 당신의 도움을!

+0

[codesandbox] (https://codesandbox.io/s/new)에서 문제를 설명하는 기능적 예를 게시하십시오. 자세한 내용은 [최소 완전하고 검증 가능한 예제를 만드는 방법] (http://stackoverflow.com/help/mcve)을 참조하십시오. –

답변

0

디스플레이 데이터를 가져 오기 전에 구성 요소가 마운트 될 때까지 기다릴 수 있습니까? 여기에 도움이 될 몇 가지 의사 코드입니다 :

class ViewLegos extends Component { 

    componentDidMount() { fetchLegos() } 

    render() { 
    const allowRender = this.props.store.legoParts && this.props.store.legoParts.length 

    if (allowRender) { 
     // display lego data 
    } 

    return null 
    } 

} 

이 예제에서, 우리는 구성 요소가 마운트 데이터를 가져 오기 위해 기다린가 존재하는 경우에만 표시됩니다.

코드를 살펴보면 legoParts가 아직 정의되지 않은 경우보다 방어적이고 구성 요소 디스플레이를 처리해야하는 것처럼 보입니다. 렌더링 전에 비동기 가져 오기가 완료되지 않기 때문에 처음에는 정의되지 않습니다.