[英]react-native re-run function on navigating back
我正在使用react-navigation在屏幕之間導航,現在在我的“ cases.js”中,我有一個fetch方法,當用戶單擊它時,它會從API中獲取案例,當該案例加載帶有點擊案例的另一頁時,它可以接受或接受否認案件本身。
無論哪種方式,如果用戶接受該案例,那么該用戶將被重定向到“ cases.js”頁面,而我不再需要該案例在“ cases.js”頁面列表中可用。
這是我的cases.js文件
export default class PendingCases extends Component {
constructor(props) {
super(props);
this.state = { cases : [], user : '', refreshing : false }
}
componentDidMount = async () => {
await this._getUser();
await this._getCases();
}
_getUser = async () => {
let user = await AsyncStorage.getItem('user');
await this.setState({ user : JSON.parse(user) })
}
_getCases = async () => {
try {
await this.setState({ refreshing : true })
let pendingCases = await fetch('http://192.168.1.101:1337/user/cases?status=pending&userType=patient&id=' + this.state.user.id);
let response = await pendingCases.json();
await this.setState({ cases : response.cases });
await this.setState({ refreshing : false })
} catch (err) {
console.log(err);
}
}
render() {
let casesArray = this.state.cases.map((singleCase, index) => {
return (
<View key={ index }>
<TouchableOpacity onPress={ () => this.props.navigation.navigate('SelectedCaseDetails') } style={ styles.caseButton }>
<View>
<View style={{ marginBottom: 10, marginTop: 5 }}>
<LinearTextGradient locations={[0, 1]} start={{x: 0, y: 0}} end={{x: 1, y: 0}} colors={['#a4d294', '#3ac6f3']} style={{ fontWeight: 'bold' }}>
{singleCase.doctor.name}
</LinearTextGradient>
<Text style={{ position: 'absolute', right: 0, fontWeight: '600', color: 'black'}}> 00231 </Text>
</View>
<View style={{ marginBottom: 10 }}>
<Text> {singleCase.additionalInformation} </Text>
</View>
<View style={{ marginBottom: 10, flex : 1, flexDirection: 'row'}}>
<Image style={ styles.statusImage } source={require('../images/status.png')} />
<Text style={{ marginRight : 30, color : 'rgba(0, 0, 0, .8)', flex : 8}}>
Status <Text style={{ color : 'rgb(240, 151, 166)', marginLeft : 60 }}> {singleCase.status} </Text> </Text>
<Text style={{ position: 'absolute', right: 0, fontWeight: '300', color: 'grey'}}> { parsedDate } </Text>
</View>
</View>
</TouchableOpacity>
</View>
)
});
return (
<View>
{ casesArray }
</View>
)
}
}
當我從一級深層頁面重定向用戶時,如何重新運行this._getCases()
函數?
我將用戶重定向為與導航this.props.navigation.navigate('CasesScreen')
其他屏幕的方式相同this.props.navigation.navigate('CasesScreen')
如果已經安裝了組件,則可以使用react-navigation's
偵聽器檢查組件是否處於焦點狀態。
你需要
didFocus :屏幕聚焦(如果存在過渡,則過渡完成)
componentDidMount () {
this._getUser();
this._onFocusListener = this.props.navigation.addListener('didFocus', (payload) => {
this._getCases();
});
}
卸載后,將其刪除。
componentWillUnmount () {
this._onFocusListener.remove()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.