在我的主屏幕中,我有一些按钮,可以通过不同的屏幕进行测试。当用户完成测试时,分数将插入到SQLite db文件中。当用户点击“主页”返回主屏幕时,我想在结果部分显示新的分数。像这样的东西:
主屏幕(App.js):
import Test1 from './Tests/Test1";
class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
test1Score: 0,
}
//Retrieve last test score from SQLite table
//setState for test1Score
getTestScoreFromSQLiteDBAndSetState();
}
render() {
return(
<Button onPress={this.gotoTest1()} />
<Text>Last test result: {this.state.test1Score}</Text>
)}
}
Test1.js:
onTestComlete() {
//insert the test score to the SQLite table
insertTestScoreToSQLiteDB();
}
<Button onPress={navigation.navigate('HomeScreen')} title='Home' />
这是基本的设置,我不会发布完整的代码,因为它太乱了。
现在我可以将分数插入到db表中。问题出在HomeScreen中,getTestScoreFromSQLiteDBAndSetState部分仅在第一次加载应用程序时执行。因此,如果我完成Test1,然后按“Home”导航到HomeScreen,则分数不会刷新。
React Native中是否有任何技术可以实现此目的?
编辑:对于那些遇到类似问题的人,这是我根据接受的答案的#2解决方案做的:
主屏幕:
navigateToTest1 = () => {
this.props.navigation.navigate('test1', {
updateResult: this.updateTest1Results.bind(this)
});
}
updateTest1Results = () => {
//codes to retrieve result and setState goes here
}
Test1.js:
const { params } = this.props.navigation.state;
params.updateResult();
发生的事情就是当你回去的时候react-navigation
没有再次加载你的屏幕只是为了更好的表现而显示之前的内容。你有很多可能性,其中一些看起来像这样:
1-而不是使用navigation.navigate()
使用navigation.push()
将创建一个新的屏幕,所以它将更新任何更新。
2-您可以在导航之前从test1.js
调用homeScreen
上的函数,只需将函数从homescreen
传递给test
作为参数或作为道具(我不知道它是如何构造的)。在该函数上只有你想要更新的内容,所以调用sqlite表和setState
3-使用react-navigation
事件。
<NavigationEvents
onWillFocus={payload => console.log('will focus',payload)}
onDidFocus={payload => console.log('did focus',payload)}
onWillBlur={payload => console.log('will blur',payload)}
onDidBlur={payload => console.log('did blur',payload)}
/>
有关react-navigation
事件的更多信息,请参阅this
有关navigation.push()
的更多信息,请参阅this