我正在使用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')
相同的方式重定向用户
如果已安装组件,则可以使用react-navigation's
listeners检查组件是否已聚焦。
你需要
didFocus:屏幕聚焦(如果有转换,转换完成)
componentDidMount () {
this._getUser();
this._onFocusListener = this.props.navigation.addListener('didFocus', (payload) => {
this._getCases();
});
}
卸载组件后删除它。
componentWillUnmount () {
this._onFocusListener.remove()
}