我有一個看起來像這樣的組件:刷新在反應路由器,組件的生命週期
class ThingView extends Component {
constructor(props) {
super(props)
}
componentWillMount() {
this.props.loadThingThenFrames(this.props.id)
}
componentDidUpdate(prevProps) {
console.log("did update")
if (prevProps.id !== this.props.id) {
this.props.loadThingThenFrames(this.props.id)
}
}
render() {
return (
<div className="container">
{ this.props.isRequesting ? <p>Loading thing...</p> : null}
<h1> {this.props.thing ? this.props.thing.device_id : "Thing Not Found"} </h1>
<Timeline frames={this.props.frames} />
</div>
)
}
}
const mapStateToProps = (state, ownProps) => ({
thing: state.thingView.thing,
frames: state.thingView.frames,
id: ownProps.params.id,
isRequesting: state.thingView.isRequesting,
requestError: state.thingView.requestError
})
const mapDispatchToProps = (dispatch) => ({
loadThingThenFrames: (id) => { dispatch(loadThingThenFrames(id)) }
})
該組件被渲染時things/:id
。根據react-router docs,componentDidUpdate
在道具被改變時被調用,例如當從事物列表中選擇事物時。我想loadThingThenFrames
頁面刷新時,或者如果有人離開ThingView
,然後回到ThingView
與thing
相同。目前,這並沒有發生,因爲前面的props.id
和當前的props.id
是一樣的,如果我刪除這個檢查,那麼會有一個無限循環的道具被更新,並且componentDidUpdate
被調用。