问题描述
我是本机开发的新手,已经花了2天的时间解决此问题。我的打字不好,但是我可以用源代码解释问题。
当前情况:
-
应用程序的主屏幕: 有用于停靠特定卡的停靠图标。在单击扩展坞图标后,该卡作为扩展坞列表存储在数据库中。一切正常。
-
在主屏幕上,有诸如切换到Docklist之类的链接: 当我单击“ Docklist”时,它将在“ Docklist”屏幕上重定向,一切正常。
-
在DockList屏幕上,有4张卡,例如“卡a”,“查看底座列表”,“卡c”,“卡d”
在此屏幕上执行的步骤:
- componentDidMount()
问题领域:
这是我的源代码:
componentDidMount() {
console.log("ComponentDidmount called")
AsyncStorage.getItem('Id').then(value => {
if (value !== null) {
this.setState({ profileId: value })
}
})
this.getDockedData();
}
getDockedData = async () => {
this.showLoading();
console.log("API CALLED=====")
try {
let axiosConfig = {
headers: {
'Access-Control-Allow-Origin': '*'
},params: {
pId: this.state.profileId,}
}
axios.get('apiendpoint',axiosConfig)
.then((res) => {
this.setState({
sourceData: [...res.data.filter((item) => { if (!item.s_updated && !item.b_updated && !item.p_updated) return item })],});
console.log("Data from dock api====",this.state.sourceData)
this.hideLoading();
})
.catch((err) => {
console.log("AXIOS ERROR WHILE GETTING DOCK DATA: ",err);
this.hideLoading();
})
}
catch (error) {
console.log("ERROR======",error);
this.hideLoading();
}
}
forceUpdate() {
console.log("Force update called===")
this.getDockedData();
}
//On render I am calling component
<Dockcomp description="Lorum ipsum" onButtonPress={() => this.props.navigation.navigate('dockdetailscreen',{ item: sourceData,type: "docked",UpdateUI: this.UpdateUI },this.forceUpdate())} />
预期的响应:
- 主屏幕->我从主屏幕停靠了一张卡片
- 在主屏幕上->单击“切换到DockList”->导航到Dock屏幕
- 在Dock屏幕上->单击“查看Dock列表”->每当我单击“查看Dock列表”时,都应该调用api。现在只调用一次,因为我使用了componentDidMount()
非常感谢您!从过去的两天开始,我真的为此而苦苦挣扎。
解决方法
您不需要重新渲染。一旦使组件成为焦点,就可以编写一个侦听器来触发getDockedData。像这样的东西:
componentDidMount() {
this.unsubscribe = navigation.addListener('focus',() => {
// stuff you are already doing in componentDidmount
});
}
componentWillUnmount() {
this.unsubscribe();
}
您可以了解有关监听器和导航事件here
的更多信息 ,React 和 React-Native 使用 shadowDOM 来评估何时触发重新渲染。除非强制,否则仅在组件的 state 或 prop 更改时才会重新渲染。在这一点上,在树中进行浅层比较以查看是否需要重新渲染。所以如果要调用重新渲染,可以在 componentDidMount 中添加一个触发状态更改的侦听器。或者其他任何地方。