我正在使用React Router创建一个应用程序,其中包含多个路由,包括一个名为
以下是进行路由的主要应用程序:
Uploader
的组件,用于上传视频,以及一个名为Videos
的组件,用于查看视频。 视频页面将某些评论存储为状态,并希望在整个应用程序打开期间保留在该页面上。但是,React Router似乎导致每个组件重新挂载而不是重新渲染,这会导致每次重新路由回Video
组件时将我的状态重置为初始空值。我在我的组件中使用render
方法而不是component
方法,因此我不理解为什么会发生这种情况。有人知道产生这种情况的原因吗?以下是进行路由的主要应用程序:
class App extends React.Component{
constructor(props){
super(props)
var fileNames
var files
var fileSelected
this.state={fileSelected:null}
}
getFileFromChild= (uploadedFiles)=> {
this.files = uploadedFiles
}
fileButtonClicked= (index)=> {
//extract file chosen by user based on button click
this.setState({fileSelected: this.files[0][index]})
}
render(){
//destructuring props in class component
const {user} = this.props;
return(
<Router>
<div className = "nav-bar">
<Nav/>
<Switch>
<Route path='/' exact render={()=> <HomePage />
}/>
<Route path='/videos' render={()=> <Videos files= {this.files} fileSelected={this.state.fileSelected}/>
}/>
<Route path='/uploader' render={()=> <Uploader passFile= {this.getFileFromChild} fileButtonClicked={this.fileButtonClicked}/>
} />
</Switch>
</div>
</Router>
)
}
}
这里是 Videos
组件,其中存储了我需要的状态:
class Videos extends React.Component{
constructor(props){
super(props)
this.videoRef = React.createRef();
}
// once DOM loads get video tag and reload it
componentDidUpdate(){
this.videoRef.current.load()
}
render(){
const {files, fileSelected}=this.props;
var src = (fileSelected) ? URL.createObjectURL(fileSelected): URL.createObjectURL(files[0][0])
return(
<div>
<div className="ui one column centered grid">
<div className="one wide column"> {/*needs to be one wide here not just column for center to work*/}
<h3>Videos</h3>
</div>
</div>
<div className="ui grid">
<div className="ten wide column">
<video ref={this.videoRef} controls width="566" height="320">
<source src={src} id='video' type="video/mp4" />
Your browser does not support HTML5 video.
</video>
<CommentsSection/>
</div>
<div className="six wide column">
{files[1]}
</div>
</div>
</div>
)
}
}
component
,而是使用render
,所以我不应该看到这种行为,对吧? - Sean Barkercomponent
在属性变化时会卸载/挂载,但render
不会在属性变化时卸载/挂载。两者都会在路由变化时进行卸载/挂载。在官方文档中,“每次渲染”并不是指路由变化,而是指属性变化(会触发渲染)。 - hwkdcomponent
属性替换为render
。谢谢! - Jonas Rosenqvist