Reactjs 在react路由器、组件生命周期中刷新
我有一个组件如下所示:Reactjs 在react路由器、组件生命周期中刷新,reactjs,redux,react-router,Reactjs,Redux,React Router,我有一个组件如下所示: class ThingView extends Component { constructor(props) { super(props) } componentWillMount() { this.props.loadThingThenFrames(this.props.id) } componentDidUpdate(prevProps) { console.log("did up
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)) }
})
类ThingView扩展组件{
建造师(道具){
超级(道具)
}
组件willmount(){
this.props.loadThingThenFrames(this.props.id)
}
componentDidUpdate(prevProps){
日志(“did更新”)
if(prevProps.id!==此.props.id){
this.props.loadThingThenFrames(this.props.id)
}
}
render(){
返回(
{this.props.isRequesting?正在加载东西…:null}
{this.props.thing?this.props.thing.device_id:“找不到东西”}
)
}
}
const mapStateToProps=(state,ownProps)=>({
事物:state.thingView.thing,
帧:state.thingView.frames,
id:ownProps.params.id,
isRequesting:state.thingView.isRequesting,
requestError:state.thingView.requestError
})
const mapDispatchToProps=(调度)=>({
loadThingThenFrames:(id)=>{dispatch(loadThingThenFrames(id))}
})
当
things/:id
时,将呈现此组件。根据componentDidUpdate在道具更改时被调用,例如,当从事物列表中选择某个事物时。当页面刷新时,或者如果有人离开ThingView
,然后带着同样的东西回到ThingView
,我想loadthingtenframes
。目前,这不会发生,因为如果我删除此检查,以前的props.id
与当前的props.id
相同,然后,会有一个无限循环的道具得到更新,并调用componentdiddupdate
。它认为问题在于,初始渲染(安装组件时)不会调用componentdiddupdate
——只有在重新渲染组件时才会调用它。所以,在页面刷新后或返回组件路由时,不会调用它,因为组件是在这种情况下装入的(不会重新呈现)——组件的新实例被创建并插入到DOM中
因此,除了在组件更新时调用loadThingThenFrames
外,还应该在组件装入时调用loadThingThenFrames
——在组件构造函数中或在装入组件时调用的另一个生命周期方法(componentWillMount
或componentDidMount
)。请查看有关ccomponents生命周期的更多详细信息