我有两个组件,即Project组件和MainContainer。 Maincontainer将使用fetchData方法一次又一次地获取数据,因此在这种情况下,我可以在前进时更改URL以及组件,但是在后退过程中它不会更改组件,但URL可以更改。
项目组件:
conditionalRendering(project) {
let text;
if (project.attributes.folder_id) {
text = <Link to={`/folder/${project.attributes.folder_id}`}>
{project.attributes.name}</Link>
} else {
text = <span>{project.attributes.name}</span>
}
return text;
}
MainContainer组件:
componentDidMount() {
const paths = this.props.location.pathname.split('/')
const id = paths[paths.length - 1]
console.log('componentDidMount')
axios.get(this.state.url, {
params: {
folder_id: id
}
})
.then(response => {
console.log('Axios response of componentdid mount')
console.log(response)
this.setState({
isLoading: !this.state.isLoading,
documents: response.data.data
})
})
}
fetchData(folder_id) {
this.setState({
isLoading: true,
})
console.log('updating state fetch data')
axios.get(this.state.url, {
params: {
folder_id: folder_id
}
})
.then(response => {
console.log('Axios response inside fetchData')
console.log(response)
this.setState({
isLoading: false,
documents: response.data.data,
})
})
}
selectRow(document) {
this.setState({
selectedRow: true,
rowDetails: document
})
}
componentDidUpdate(prevProps, prevState){
console.log('componentDidUpdate')
if (prevState.isLoading === false) {
console.log('if will run isLoading is false')
this.setState({ isLoading: true })
console.log('if will run isLoading is true' )
const paths = this.props.location.pathname.split('/')
const id = paths[paths.length - 1]
axios.get(this.state.url, {
params: {
folder_id: id
}
})
.then(response => {
console.log('Axios response componentdidupdate')
console.log(response)
this.setState({
isLoading: !this.state.isLoading,
documents: response.data.data
})
})
}
}
documentsCollection() {
let documentComponents;
if (this.state.documents.length > 0 ) {
documentComponents = this.state.documents.map(document => {
return (
<tr key={document.id} onClick={() => this.selectRow(document)}>
<span className="file-thumbnail float-right"><i className={document.attributes.is_folder ? 'fas fa-folder' : 'far fa-file'}></i></span>
<td data-label="Name">
<Link to={`/folder/${document.attributes.id}`} onClick={() => this.fetchData(document.attributes.id)}>{document.attributes.filename}</Link>
</tr>
)
})
return documentComponents;
}
}
路由器组件:
<Switch>
<Route exact path="/" component= {Project} />
<Route path="/folder/:id" component= {MainContainer} />
</Switch>
答案 0 :(得分:0)
如果您已经在Maincontainer中,并且仅id值已更改,则componentDidMount将不会被激活。请使用componentDidUpdate并比较道具。