2016-07-25 2 views
3

나의 본능은 나에게 말한다. 그러나 나는 더 좋은 길을 생각하기가 어렵다.componentWillReceiveProps 내에서 작업을 호출해야합니까?

현재 항목 목록을 표시하는 구성 요소가 있습니다. 다음과 같이 제공 props에 따라,이 목록은 새 this.props.type 주어진 (즉, 필터링 변화 나 상황 변화에) 예를 들어

을 변경할 수 있으며, 상태를 업데이트한다 :

componentWillReceiveProps(nextProps) { 
     if (nextProps.type == this.state.filters.type) return 

     this.setState({ 
      filters: { 
       ...this.state.filters, 
       type: nextProps.type, 
      }, 
      items: ItemsStore.getItems().filter(item => item.type == nextProps.type) 
     }) 
} 

이 모두 미세하며 좋아,하지만 지금은 내 요구 사항이 변경되어 새로운 필터를 추가해야합니다. 새 필터의 경우 올바른 항목 ID 목록을 반환하는 API 호출을 실행해야하며 동일한 ID가있는 항목 만 같은 목록 구성 요소에 표시하고 싶습니다. 이 문제를 어떻게 해결해야합니까?

나는 적절한 조치를 componentWillReceiveProps에서 호출하는 것에 대해 생각해 왔지만 그것이 옳은 것처럼 보입니다.

componentWillReceiveProps(nextProps) { 
     if (nextProps.type == this.state.filters.type && nextProps.otherFilter == this.state.filters.otherFilter) return 

     if (nextProps.otherFilter != this.state.filters.otherFilter) { 
      ItemsActions.getValidIdsForOtherFilter(nextProps.otherFilter) 
      // items will be properly updated in store change listener, onStoreChange below 
     } 

     this.setState({ 
      filters: { 
       ...this.state.filters, 
       type: nextProps.type, 
       otherFilter: nextProps.otherFilter, 
      }, 
      items: ItemsStore.getItems().filter(item => item.type == nextProps.type) 
     }) 
}, 

onStoreChange() { 
    let validIds = ItemsStore.getValidIds() 

    this.setState({ 
     items: ItemsStore.getItems().filter(item => item.type == this.state.filters.type && validIds.indexOf(item.id) > -1) 
    }) 
} 
+0

API 호출을 한 번만 실행하려면 componentWillMount() 또는 componentDidMount()에서 수행하십시오. –

+0

불행히도 API 호출은 매번 this.props를 실행해야합니다. otherFilter'가 업데이트됩니다. –

답변

8

업데이트 2018년 1월 22일 :

최근 RFC-PR for React was merged, 곧 비동기 렌더링 모드에서 사용할 때 unsave 될 수 componentWillReceiveProps을 deprecates. 이에 대한 예는이 라이프 사이클 후크에서 플럭스 액션을 호출하는 것일 수 있습니다.

작업을 호출하는 올바른 위치 (즉, side effects)는 React is done 렌더링 이후이므로 componentDidMount 또는 componentDidUpdate을 의미합니다.

조치의 의도가 데이터를 가져 오는 것이라면, React는 향후 이러한 것에 대한 새로운 전략을 지원할 수 있습니다. 그 동안 언급 된 두 라이프 사이클 후크를 고수하는 것이 안전합니다.

+0

흠 ... 실제로 그것이 가장 좋은 방법 인 것 같습니다. 감사. –