javascript - React Native 中的屏幕不会自动刷新
问题描述
async componentDidMount () {
this._isMounted = true;
await this.showPosts();
}
componentDidUpdate () {
this.showPosts();
}
showPosts = async () => {
try {
var userID = await AsyncStorage.getItem('userID');
fetch(strings.baseUri+"getPostWithUserID", {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"user_id": userID
})
})
.then((response) => response.json())
.then((responseJson) => {
let jsonObj = JSON.parse(JSON.stringify(responseJson));
if (jsonObj.status=="true") {
this.setState({
data: responseJson.data,
imageSrc: responseJson.data.imgSrc,
});
}
else {
if (this._isMounted) {
this.setState({show: false});
}
}
})
.catch((error) => {
console.error(error);
});
}
catch (err) {
console.warn(err);
}
}
componentWillUnmount () {
this._isMounted = false;
}
showPosts
是我的函数,它获取数据并将其显示到平面列表中。
<FlatList
data={this.state.data}
keyExtractor={(index) => index.toString()}
renderItem={ ({item,index}) => this._renderItem(item,index) }
extraData={[ this.state.checked, this.state.data ]}
/>
- 现在,当我上传一篇帖子并返回我的主屏幕时,它会调用
showPosts
并通过再次重新加载应用程序在我的模拟器上检查它,它会向我显示该帖子。 - 现在,当我上传另一个帖子并返回主屏幕时,我不需要在模拟器中重新加载我的应用程序,但我
componentDidUpdate
会被调用并自动刷新屏幕并向我显示新帖子。
我的问题是,当主屏幕上的帖子为零时,为什么我必须再次重新加载(通过多次按 R 重新加载)我的应用程序。我希望在我上传第一篇文章时自动更新我的屏幕。只有在超过 1 个帖子的情况下,屏幕才会自动更新。
PS - 我也试过onRefresh()
了,对我的问题没有帮助。
解决方案
利用forceUpdate()
请检查此链接:https ://reactjs.org/docs/react-component.html#forceupdate
推荐阅读
- java - java中的异常,打印一个列表
- git - Git子模块,仅添加忽略的目录
- javascript - 试图将 h1 text.event 保存到变量中,因此当您键入它保存的第一个字母时
- flutter - 有没有办法将 RoundedRectangleBorder 半径的相对大小放入 Flutter 中?
- mysql - MySQL:因为索引/FKEY 导致 SELECT 慢?
- android - 尝试运行应用程序时在 android studio 中出现找不到方法错误
- python - 将字典列表中的字符串更改为整数
- github - 有没有办法在 Microsoft 团队中获取 Github 拉取请求通知?
- reactjs - React-Native expo 调试错误未显示任何有用信息或错误消息
- go - 使用通道退出永远循环 - Go Playground 的问题