Javascript 在ReactJS和react路由器中更改路由状态?
在我的Javascript 在ReactJS和react路由器中更改路由状态?,javascript,reactjs,react-router,axios,Javascript,Reactjs,React Router,Axios,在我的App.js文件中,我正在导入一个Page.js组件,并使用将其放置在页面上。在页面组件中,我设置了一个相对于该组件的状态。当用户选择新页面时,我使用react router 我正在设置的状态正在从一页传递到另一页,当页面更改时,我需要重置我的状态。我尝试过在componentDidMount()、componentWillMount()、componentWillUnmount()、和componentdiddupdate()内部执行setState({archive:[]),但它们要么
App.js
文件中,我正在导入一个Page.js
组件,并使用
将其放置在页面上。在页面组件中,我设置了一个相对于该组件的状态。当用户选择新页面时,我使用react router
我正在设置的状态正在从一页传递到另一页,当页面更改时,我需要重置我的状态。我尝试过在componentDidMount()
、componentWillMount()
、componentWillUnmount()
、和componentdiddupdate()
内部执行setState({archive:[])
,但它们要么不起作用,要么导致错误
更新:
我已经更新了一点代码。我在我的构造函数中设置了这个.archiveData
constructor(props) {
super(props);
this.state = {
title: 'David Powell',
nav: {},
currentPage: "",
pageContent: "",
pageTitle: "",
pageTemplate: "",
pageId: 0,
pageCustomMeta: {},
archiveData: []
}
}
调用页面时,我根据api返回的内容设置值。我正在重置archivedData
,因为它是根据作为道具传递给页面组件的内容填充的
getPageData(slug){
console.log(this.state);
axios.get('http://admin.sitedata.co/pages?slug='+slug)
.then((response) => {
console.log(response.data);
this.setState({
pageContent:response.data[0].content.rendered,
currentPage:slug,
pageTitle:response.data[0].title.rendered,
pageTemplate:response.data[0].template,
pageId:response.data[0].id,
pageCustomMeta:response.data[0].post_meta,
archiveData:[]
},function(){
console.log(this.state);
/*
* set the page title
* check if the page is at home
* get page custom meta
*/
document.title = this.state.pageTitle;
this.isHome();
//this.getPageCustomMeta(this.state.pageId);
});
})
.catch((error) => {
console.log(error);
});
}
所有内容都得到了正确更新:页面内容更改、标题更新等。console.log
显示archiveData
为空,但页面本身没有更新,它仍然存在。请提供更多代码。当安装组件时,它首先不应该有一个状态,除非你在安装之前故意添加它。React路由器在路由时传递数据组件,它不保持传递状态。当然需要更多的代码。路由目标组件的道具中应该有一个路由对象。问题用代码和更多信息更新。这是一篇旧文章。我不确定你是否还需要帮助。如果是这样的话,请尝试在服务器上重新创建此文件。这将使任何人都能清楚地了解代码的功能,并有助于调试。请提供更多代码。当组件装载时,它首先不应该有状态,除非您在装载前有意添加它。React路由器在路由时传递数据组件,它不保持传递状态。当然需要更多的代码。路由目标组件的道具中应该有一个路由对象。问题用代码和更多信息更新。这是一篇旧文章。我不确定你是否还需要帮助。如果是这样的话,请尝试在服务器上重新创建此文件。这将使任何想要排除故障的人清楚地了解代码的功能,并有助于调试。