react-native - 如何在 react-native 中重新渲染组件?
问题描述
我是 react-native 开发的新手,已经为这个问题花了 2 天时间。我不擅长打字,但我可以用我的源代码解释问题。
当前情景:
应用程序的主屏幕:有用于停靠特定卡的停靠图标。单击停靠图标后,该卡作为停靠列表存储在数据库中。它工作正常。
在主屏幕上有诸如切换到 Docklist 之类的链接:当我单击停靠列表时,它将重定向到停靠列表屏幕上,它工作正常。
在 DockList 屏幕上有 4 张卡片,例如“Card a”、“查看停靠列表”、“Card c”、“Card d”
在此屏幕上执行的步骤:
- 组件DidMount()
- 在 componentDidMount() 上,我从 AsyncStorage(Local Storage) 获取“ID”并将该值设置为状态。我将此 ID 传递给 api 参数。
- 调用服务器 API (this.viewDockList())
问题领域:
- 根据我的知识和研究,componentDidMount() 在渲染后只调用一次。
- 当我随时单击“查看 DockList”时,我需要调用 api。
- 在这里,当我刷新应用程序时,以下场景正在运行
主屏幕-> 我从主屏幕停靠了一张卡片
在主屏幕上 -> 单击“切换到 DockList” -> 导航到 Dock 屏幕
在 Dock 屏幕上 -> 单击“查看 Dock List” -> 第一次调用 api 并根据我的要求显示数据。
现在,我回到主屏幕,再次停靠卡并导航到停靠屏幕并单击查看停靠列表,当时 Api 没有调用,只有 render() 正在调用。这里我需要再次调用 API 并从服务器获取最新数据。我试图在单击“查看停靠详细信息”时调用强制更新,调用 api 但未更新列表。
这是我的源代码:
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 Screen -> 点击“View Dock List” -> 每当我点击 View Dock list 时,应该调用 api。现在它只调用一次,因为我使用了 componentDidMount()
非常感谢您!我真的在过去两天为这个问题苦苦挣扎。
解决方案
React 和 React-Native 使用 shadowDOM 来评估何时触发重新渲染。除非强制,否则仅当组件的状态或道具发生更改时才会重新渲染。此时,在 Tree 中进行浅比较,以查看是否需要重新渲染。所以如果你想调用重新渲染,你可以在componentDidMount中添加一个监听器来触发状态改变。或者其他任何地方。
推荐阅读
- groovy - 将运行时提示从 PBCS Groovy 业务规则传递到调用的业务规则的参数(非 Groovy)
- coldfusion - 如何在导出到 Excel 之前更改 cfquery 结果的值?
- html - 如何在调整浏览器窗口大小时制作不制动和水平滚动的 HTML 页面
- php - Laravel 6.4:__toString() 必须返回一个字符串值
- ios - 如何将标签/属性添加到 XCUITest(Swift)
- java - Java中Wallis函数的递归实现
- javascript - Javascript:子/子对象应该使用由其父对象实例化的依赖项,还是应该实例化自己的依赖项实例?
- javascript - 使用 sequelize findAll 时,forEach 找不到正确的用户 ID
- php - PHP DateTime 在 WHILE 循环期间写出值
- c - 在 C 中打印二维手机键盘中的每个解锁图案