Browse Source
This question showed there was a use-case that I wasn't covering fully enough before, so I've added a new section.main
Brian Vaughn
7 years ago
6 changed files with 129 additions and 36 deletions
@ -0,0 +1,55 @@ |
|||
// After
|
|||
class ExampleComponent extends React.Component { |
|||
state = { |
|||
externalData: null, |
|||
}; |
|||
|
|||
// highlight-range{1-13}
|
|||
static getDerivedStateFromProps(nextProps, prevState) { |
|||
// Store prevId in state so we can compare when props change.
|
|||
// Clear out previously-loaded data (so we don't render stale stuff).
|
|||
if (nextProps.id !== prevState.prevId) { |
|||
return { |
|||
externalData: null, |
|||
prevId: nextProps.id, |
|||
}; |
|||
} |
|||
|
|||
// No state update necessary
|
|||
return null; |
|||
} |
|||
|
|||
componentDidMount() { |
|||
this._loadAsyncData(); |
|||
} |
|||
|
|||
// highlight-range{1-5}
|
|||
componentDidUpdate(prevProps, prevState) { |
|||
if (prevState.externalData === null) { |
|||
this._loadAsyncData(); |
|||
} |
|||
} |
|||
|
|||
componentWillUnmount() { |
|||
if (this._asyncRequest) { |
|||
this._asyncRequest.cancel(); |
|||
} |
|||
} |
|||
|
|||
render() { |
|||
if (this.state.externalData === null) { |
|||
// Render loading state ...
|
|||
} else { |
|||
// Render real UI ...
|
|||
} |
|||
} |
|||
|
|||
_loadAsyncData() { |
|||
this._asyncRequest = asyncLoadData(this.props.id).then( |
|||
externalData => { |
|||
this._asyncRequest = null; |
|||
this.setState({externalData}); |
|||
} |
|||
); |
|||
} |
|||
} |
@ -0,0 +1,41 @@ |
|||
// Before
|
|||
class ExampleComponent extends React.Component { |
|||
state = { |
|||
externalData: null, |
|||
}; |
|||
|
|||
componentDidMount() { |
|||
this._loadAsyncData(); |
|||
} |
|||
|
|||
// highlight-range{1-6}
|
|||
componentWillReceiveProps(nextProps) { |
|||
if (nextProps.id !== this.props.id) { |
|||
this.setState({externalData: null}); |
|||
this._loadAsyncData(); |
|||
} |
|||
} |
|||
|
|||
componentWillUnmount() { |
|||
if (this._asyncRequest) { |
|||
this._asyncRequest.cancel(); |
|||
} |
|||
} |
|||
|
|||
render() { |
|||
if (this.state.externalData === null) { |
|||
// Render loading state ...
|
|||
} else { |
|||
// Render real UI ...
|
|||
} |
|||
} |
|||
|
|||
_loadAsyncData() { |
|||
this._asyncRequest = asyncLoadData(this.props.id).then( |
|||
externalData => { |
|||
this._asyncRequest = null; |
|||
this.setState({externalData}); |
|||
} |
|||
); |
|||
} |
|||
} |
Loading…
Reference in new issue