2017-02-17 40 views
0

我有一個看起來像這樣的組件:刷新在反應路由器,組件的生命週期

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,然後回到ThingViewthing相同。目前,這並沒有發生,因爲前面的props.id和當前的props.id是一樣的,如果我刪除這個檢查,那麼會有一個無限循環的道具被更新,並且componentDidUpdate被調用。

回答

1

它認爲問題在於componentDidUpdate未被初始渲染調用(當組件被掛載時) - 僅在重新渲染組件時才調用它。所以它不會在頁面刷新後或者當你回到組件路由之後被調用,因爲組件在這種情況下被掛載(不重新呈現) - 組件的新實例被創建並被插入到DOM中。

因此,除了調用loadThingThenFrames當組件更新,你也應該叫loadThingThenFrames當組件安裝 - 在組件構造函數或當組件安裝(componentWillMountcomponentDidMount)被稱爲另一種生命週期方法。請查詢React docs瞭解更多關於ccomponents生命週期的細節。