2017-12-16 12 views
0

나는 현재 반작용 배우고, 어떤 물건 초보자를위한 너무 쉽게되지 않습니다 :React : "this.state.x"를 함수로 사용하기 전에 데이터를 대기시키는 법? <p></p> 내가이 (가 <strong>기능 <code>getSlots</code></strong>에 <code>li</code> 배열 덕분에 렌더링 있습니다) <code>renders</code> 간단한 구성 요소를 가지고 ...

render() { 
    return (
     <ul> 
      {this.getSlots(this.state.viewing).map(item => <li key={item}>{item}</li>)} 
     </ul> 
    ) 
    } 

getSlots 기능은 :

constructor (props) {...} 

getSlots (viewing) { 

    SOME STUFF... 

    const monday = this.state.house.monday 

    return SOME STUFF... 
    } 

componentDidMount() {...} 

render() {...} 

포인트가있다 getSlotscomponendDidMount에 가져올 데이터가 필요합니다. 사실이 시점에서 데이터를 가져 오기 전에 실행되기 때문에 getSlots이 작동하지 않습니다 (충돌합니다) (실행시 this.state.house.monday이 "비어 있음").

getSlots을 실행하기 전에 데이터를 가져올 때까지 기다리는 방법은 무엇입니까? 당신의 단서를 가져 주셔서 감사합니다. 데이터가

getSlots (viewing) { 

    if (!this.state.house) { 
     return []; 
    } 

    SOME STUFF... 

    const monday = this.state.house.monday 

    return SOME STUFF... 
    } 

때 가져온인지 아닌지

+1

'this.state.house'가 예상 한 것과 다른 경우 빈 배열을 반환하십시오. – Bergi

답변

1

조건부 렌더링이 필요합니다. 비동기 적으로 필요한 데이터를로드하기 전에로드 할로드 상태를 제공하십시오. 그런

class WrapperComponent extends PureComponent { 
    constructor(props) { 
     super(props); 

     this.state = { 
      isLoaded: false, 
      data: null 
     }; 
    } 

    componentDidMount() { 
     MyApiCall.then(
      res => this.setState({ 
       // using spread operator, you will need transform-object-rest-spread from babel or 
       // another transpiler to use this 
       ...this.state, // spreading in state for future proofing 
       isLoaded: true, 
       data: res.data 
      }) 
     ); 
    } 

    render() { 
     const { isLoaded, data } = this.state; 
     return (
      { 
       isLoaded ? 
        <PresentaionComponentThatRequiresAsyncData data={ data } /> : 
        <LoadingSpinner /> // or whatever loading state you want, could be null 
      } 
     ); 
    } 
} 
+0

그것은 매력처럼 작동합니다. @Maxim Saenko의 솔루션도 작동합니다. 또 하나의 질문은 이것에 연결되어 있지만'react router'를 사용하는 것입니다. 나는이 경로를 ()} />'와 같이 사용한다. 보시다시피, 저는'국가 '와'otherData'를 전달합니다. 나는 'this.props.otherData'로'otherData'를 검색하기 위해'Schedule' 구성 요소에서 성공합니다. 또한 '상태'에서 '물건'을 검색 할 수 있지만 DB에서 먼저 가져와야하는 항목은 검색 할 수 없습니다. 이 데이터를 다시 기다리는 방법은 무엇입니까? – nerotulip

+0

비동기 적으로 데이터를로드 할 때마다 미리로드 된 상태와로드 된 상태를 제공해야합니다. 조건부 렌더링은 친구입니다! 좀 더 명확한 지침이 필요하면 알려주십시오. –

+0

나는 그것을 얻는다라고 생각한다, 그것은 일한다. 내 경로 :' ()} />'그리고'Schedule' 구성 요소에서 조건부 렌더링 설명 :'{this.props.areSlotsReady && this.getSlots (this.props.viewing) .map (item =>

  • {item}
  • )}'. 감사. – nerotulip

    0

    constructor(){ 
    ...., 
    this.state = { house: null} 
    } 
    

    처럼 constructor에, 인출하기 전에 빈 데이터와 상태를 초기화하고 검사 getSlots 방법에 조건을 넣을 수 있습니다 데이터가 도착하면이 상태를 간단히 설정하십시오.

    componentDidMount(){ 
        fetch().then((houses) => { 
         this.setState({ houses: houses }) 
        }) 
    } 
    
    0
    constructor() { 
        super() 
        this.state = { isLoading: true } 
    } 
    
    componentDidMount() { 
        ('fetch data').then(() => { this.setState({ isLoading: false }); }) 
    } 
    
    render() { 
        return (
        <div> 
         {!this.state.isLoading && ('your code')} 
        </div> 
    ); 
    } 
    

    뭔가 : 당신은 다음과 같은 일을 할 것입니다.