나의 본능은 나에게 말한다. 그러나 나는 더 좋은 길을 생각하기가 어렵다.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)
})
}
API 호출을 한 번만 실행하려면 componentWillMount() 또는 componentDidMount()에서 수행하십시오. –
불행히도 API 호출은 매번 this.props를 실행해야합니다. otherFilter'가 업데이트됩니다. –