在我的React-native项目中,我声明了一个名为“ NavigationDrawerStructure.js”的Drawer导航器,以维护Drawer结构的所有堆栈。这是给出的代码-
NavigationDrawerStructure.js
class NavigationDrawerStructure extends Component {
static navigationOptions = {
header: null ,
};
toggleDrawer = () => {
this.props.navigationProps.toggleDrawer();
};
render() {
return (
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity onPress={this.toggleDrawer.bind(this)}>
{/*Donute Button Image */}
<Icon name='menu'/>
</TouchableOpacity>
</View>
);
}
}
const FirstActivity_StackNavigator = createStackNavigator({
First: {
screen: NoteMeHome,
navigationOptions: ({ navigation }) => ({
title: 'Home',
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerStyle: {
backgroundColor: '#FF9800',
},
headerTintColor: '#fff',
}),
},
ScreenInternal: {
screen: ScreenInternal,
navigationOptions: ({ navigation }) => ({
title: 'Screen With Navigation Drawer',
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerStyle: {
backgroundColor: '#FF9800',
},
headerTintColor: '#fff',
}),
},
});
const Screen2_StackNavigator = createStackNavigator({
Second: {
screen: MakeNote,
navigationOptions: ({ navigation }) => ({
title: 'Create Note',
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerStyle: {
backgroundColor: '#FF9800',
},
headerTintColor: '#fff',
}),
},
});
const Screen3_StackNavigator = createStackNavigator({
Third: {
screen: Screen3,
navigationOptions: ({ navigation }) => ({
title: 'Simple Screen 3',
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerStyle: {
backgroundColor: '#FF9800',
},
headerTintColor: '#fff',
}),
},
});
const Drawer = createDrawerNavigator({
Screen1: {
screen: FirstActivity_StackNavigator,
navigationOptions: {
drawerLabel: 'Home',
drawerIcon: (
<Icon name='home' size={24}
/>
)
},
},
Screen2: {
screen: Screen2_StackNavigator,
navigationOptions: {
drawerLabel: 'Create Note',
drawerIcon: (
<Icon name='home' size={24}
/>
)
},
},
Screen3: {
screen: Screen3_StackNavigator,
navigationOptions: {
drawerLabel: 'Simple Screen 3',
},
},
});
const DrawerNavigatorExample = createStackNavigator({
Drawer: { screen: Drawer, navigationOptions: { header: null } },
ScreenExternal: {
screen: ScreenExternal,
navigationOptions: { title: 'Screen External' },
},
});
export default createAppContainer(DrawerNavigatorExample);
在此Drawer导航器中,我已将NoteHome.js类初始化为此Drawer导航器的initiaRoute。这是该代码-
NoteMeHome.js
class NoteMeHome extends React.Component {
state = {
getValue: '',
dataSource:[],
isLoading: true,
note:'',
todo:'',
reminder:'',
tag:'',
urgent:'',
work:'',
office:'',
personal:'',
catTitle:'',
loading: true
}
async componentWillMount() {
await Font.loadAsync ({
Roboto: require('native-base/Fonts/Roboto.ttf'),
Roboto_medium: require('native-base/Fonts/Roboto_medium.ttf')
});
this.setState({loading:false});
}
getFirstApi() {
AsyncStorage.getItem("token").then(value => {
const url = BASE_URL+'last';
console.log('token:'+ value)
return fetch(url, {
method: 'GET',
headers: new Headers({
'Content-Type' : 'application/json',
'token': '68e109f0f40ca72a15e05cc22786f8e6',
'jwt': value
})
})
.then((response)=> response.json() )
.then((responseJson) => {
// console.log('####:'+responseJson[0].title)
this.setState({
dataSource: responseJson,
isLoading: false,
getValue: value
})
})
.catch((Error) => {
console.log(Error)
});
}
)
};
getSecondApi() {
AsyncStorage.getItem("token").then(value => {
const url = BASE_URL+'category';
console.log('token:'+ value)
return fetch(url, {
method: 'GET',
headers: new Headers({
'Content-Type' : 'application/json',
'token': 'abc',
'jwt': value
})
})
.then((response)=> response.json() )
.then((responseJson) => {
console.log('####:'+responseJson.cat_note)
this.setState({
isLoading: false,
getValue: value,
note: responseJson.cat_note,
todo: responseJson.cat_todo,
reminder: responseJson.cat_rem,
tag: responseJson.cat_tag,
urgent: responseJson.cat_urgent,
work: responseJson.cat_work,
office: responseJson.cat_office,
personal: responseJson.cat_personal,
statusIcon: ''
})
})
.catch((Error) => {
console.log(Error)
});
}
)
}
getCategoryTitle(catNum) {
switch(catNum) {
case "1": return "Undone";
break;
case "2": return "Done";
break;
case "3": return "Completed";
break;
case "4": return "Abandoned";
break;
}
}
getStatusIcon(catNum) {
switch(catNum) {
case '1': {
return 'https://img.icons8.com/nolan/64/000000/note.png'
break;
}
case '2': {
return 'https://img.icons8.com/nolan/64/000000/todo-list.png'
break;
}
case '3': {
return 'https://img.icons8.com/dusk/64/000000/alarm.png'
break;
}
case '4': {
return 'https://img.icons8.com/nolan/64/000000/tags.png'
break;
}
case '5': {
return 'https://img.icons8.com/dusk/64/000000/urgent-property.png'
break;
}
case '6': {
return 'https://img.icons8.com/nolan/64/000000/business.png'
break;
}
case '7': {
return 'https://img.icons8.com/nolan/64/000000/organization.png'
break;
}
case '8': {
return 'https://img.icons8.com/nolan/64/000000/employee-card.png'
break;
}
}
}
componentDidMount() {
this.getFirstApi();
this.getSecondApi();
}
static navigationOptions = ({navigation}) => ({
title: "Home",
headerLeft: <Icon name="ios-menu" style={{paddingLeft:10}}
onPress={()=>navigation.navigate('DrawerOpen')}/>,
drawerIcon:
<Image source={{uri: 'https://img.icons8.com/ultraviolet/40/000000/home.png'}}
style={styles.icon}
/>
})
render() {
const { getValue } = this.state;
if(this.state.loading) {
return(
<Root>
<AppLoading/>
</Root>
)
}
return(
this.state.isLoading
?
<View style={{flex:1, justifyContent:'center', alignItems:'center'}}>
<ActivityIndicator size="large" color="#330066" animating/>
</View>
:
<ScrollView>
<View>
<Text style={{fontSize:18, color:'#000', fontWeight: 'bold',marginTop:5, justifyContent:'center', textAlign:'center', marginBottom:10}}>Last Engagement</Text>
<View
style={{
borderBottomColor: 'black',
borderBottomWidth: 1,
width:'100%', justifyContent:'center',
alignItems:'center',
textAlign:'center'
}}
/>
<FlatList
horizontal
data={this.state.dataSource}
renderItem={this.renderItem}
keyExtractor = {(item, index) => index+""}
ItemSeparatorComponent={this.renderSeparator}
style={{height:150}}
/>
<View
style={{
borderBottomColor: 'black',
borderBottomWidth: 1,
width:'100%', justifyContent:'center',
alignItems:'center',
textAlign:'center',
marginTop:20
}}
/>
<Text style={{fontSize:18, color:'#000',fontWeight: 'bold',marginTop:5, justifyContent:'center', textAlign:'center', marginBottom:10}}>NoteMe Category</Text>
<View
style={{
borderBottomColor: 'black',
borderBottomWidth: 1,
width:'100%', justifyContent:'center',
alignItems:'center',
textAlign:'center'
}}
/>
{/* Total category List work starts */}
</View>
</ScrollView>
)
}
renderSeparator = ()=> {
return (
<View style={{height:'100%', width:1, backgroundColor:'white'}}>
</View>
)
}
renderItem = ({item}) => {
let a = this.getStatusIcon(item.category);
console.log(a);
return(
<TouchableOpacity style={{flex:1, flexDirection:'row'}}
onPress= {() => ToastAndroid.show(item.title, ToastAndroid.SHORT)}
>
<View style={styles.container2}>
<View style={{flex:1, justifyContent:'center'}}>
<Image style={{width:50, height:50, marginLeft:10, marginBottom:5, marginTop:5, marginRight:5}}
source={{uri: a}}
/>
</View>
<View style={{flex:1, justifyContent:'center', marginLeft:5, marginRight:10}}>
<Text style={{fontSize:18, fontStyle:'normal', fontWeight:'bold', color:'#2c3e50', marginBottom:5}}>
{this.getCategoryTitle(item.status)}
</Text>
<Text style={{fontSize:18, color:'#7f8c8d', marginBottom:5}}>
{item.title}
</Text>
</View>
</View>
</TouchableOpacity>
)
}
}
export default NoteMeHome;
在此类中,您可以看到我有一个API调用并获取数据并显示在flatList中。在此Drawer导航器的第二个项目中,我有一个类来发布要在上面的代码NoteMeHome.js中的第一个屏幕中显示的数据。 在第二个屏幕中,我已经完成了所有API调用,并将表单发布到服务器,如下所示-
MakeNote.js
export default class HelloWorldApp extends Component {
state = {
isLoading:false,
getValue: null,
}
constructor() {
super();
this.state = {
title:'',
detail:'',
timestamp : '',
status: '',
url:'',
mail:'',
phone:'',
category:'',
showLoader:false,
showAlert: false,
isNetConnected: true,
catImage: null,
ModalVisibleStatus: false,
ModalUrlVisibleStatus: false,
ModalPhoneVisibleStatus: false,
statusText:''
}
};
updateImage(image, category) {
this.setState({
catImage: image,
category: category
})
}
updateValue(text, field) {
if(field == 'title') {
this.setState({
title : text
})
}
else if(field == 'details') {
this.setState({
detail : text
})
}
else if(field == 'email') {
this.setState({
mail : text
})
}
else if(field == 'url') {
this.setState({
url : text
})
}
else if(field == 'phone') {
this.setState({
phone : text
})
}
}
ShowModalFunction(visible) {
this.setState({ModalVisibleStatus: visible});
}
ShowModalUrlFunction(visible) {
this.setState({ModalUrlVisibleStatus: visible});
}
ShowModalPhoneFunction(visible) {
this.setState({ModalPhoneVisibleStatus: visible});
}
// net connection starts
async componentDidMount() {
const token = await AsyncStorage.getItem('token');
this.setState({ getValue: token });
//getting current date time starts
var that = this;
var date = new Date().getDate(); //Current Date
var month = new Date().getMonth() + 1; //Current Month
var year = new Date().getFullYear(); //Current Year
var hours = new Date().getHours(); //Current Hours
var min = new Date().getMinutes(); //Current Minutes
var sec = new Date().getSeconds(); //Current Seconds
that.setState({
//Setting the value of the date time
timestamp:
date + '/' + month + '/' + year + ' ' + hours + ':' + min + ':' + sec,
});
//getting current date time ends
NetInfo.isConnected.addEventListener(
"connectionChange",
this.handleConnectivityChange
);
}
componentWillUnmount() {
NetInfo.isConnected.removeEventListener(
"connectionChange",
this.handleConnectivityChange
);
}
handleConnectivityChange = isConnected => {
if (isConnected) {
this.setState({ isConnected });
} else {
this.state.isNetConnected = false;
alert("Oops!! No Internet Connection Available");
this.setState({ isConnected });
}
};
// net connection ends
submit() {
this.setState({isLoading:true})
let collection = {}
collection.timestamp = this.state.timestamp,
collection.status = this.state.status,
collection.title = this.state.title,
collection.detail = this.state.detail,
collection.url = this.state.url,
collection.mail = this.state.mail,
collection.phone = this.state.phone,
collection.category = this.state.category
console.log('#HELLO:', collection);
var url = BASE_URL+'/notes/new';
if(collection.title != '' ) {
// this.setState({showLoader:true});
if(this.state.isNetConnected != false) {
fetch(url, {
method: 'POST',
body: JSON.stringify(collection),
headers: new Headers({
'Content-Type' : 'application/json',
'token': 'abcd',
'jwt': this.state.getValue
})
}).then(response =>
{
this.setState({isLoading:false});
console.log(response.headers.get('Content-Type'));
console.log(response.headers.get('Date'));
console.log(response.status);
console.log(response.statusText);
console.log(response.type);
console.log(response.url);
if (response.status !== 200) {
console.log('Status Code: ' + response.status);
return;
}
// Examine the text in the response
response.json().then(data =>{
console.log(data);
if(data.status == "saved") {
this.props.navigation.navigate('First');
}
});
}
)
.catch(error=>{
this.setState({isLoading:false})
console.error('Error:', error)
})
} else{
this.setState({isLoading:false});
Alert.alert("Oops!! No Internet Connection Available");
}
}
else {
this.setState({isLoading:false})
Alert.alert('Please fill up the required field');
}
}
render() {
console.log('#ZZZ2:', this.state.getValue);
return (
<View style={{flex:1}}>
<ScrollView keyboardShouldPersistTaps={'handled'}>
<View style={styles.container}>
{/* upper portion starts */}
<View style={{flexDirection:'row'}}>
<View style={{marginTop:20, marginRight:20}}>
<TouchableOpacity style={{justifyContent:'center', alignItems:'center', marginTop:20}}
onPress={()=>{this.setState({status:'1'}), this.setState({statusText:'Done'})}}
>
<Image style={styles.inputIconCategory} source={{uri: ICON_DONE}}/>
</TouchableOpacity>
<TouchableOpacity style={{justifyContent:'center', alignItems:'center', marginTop:20}}
onPress={()=>{this.setState({status:'2'}), this.setState({statusText:'Undone'})}}
>
<Image style={styles.inputIconCategory} source={{uri: ICON_UNDONE}}/>
</TouchableOpacity>
</View>
<View>
<View style={{alignItems:'center', marginTop:20}}>
<Text >{this.state.statusText}</Text>
</View>
<View style={styles.inputContainerEmail}>
<Image style={styles.inputIcon} source={{uri: this.state.catImage}}/>
<TextInput style={styles.inputs}
placeholder="Title"
keyboardType="email-address"
underlineColorAndroid='transparent'
onChangeText={(text) => this.updateValue(text, 'title')}/>
</View>
<View style={styles.inputContainerDetails}>
<TextInput style={styles.inputs}
placeholder="Details"
multiline
underlineColorAndroid='transparent'
onChangeText={(text) => this.updateValue(text, 'details')}/>
</View>
</View>
<View style={{marginTop:20, marginRight:20}}>
<TouchableOpacity style={{justifyContent:'center', alignItems:'center', marginTop:25}}
onPress={() => { this.ShowModalUrlFunction(true) }}
>
<Image style={styles.inputIconCategory} source={{uri: ICON_URL}}/>
</TouchableOpacity>
<TouchableOpacity style={{justifyContent:'center', alignItems:'center', marginTop:25}}
onPress={() => { this.ShowModalFunction(true) }}
>
<Image style={styles.inputIconCategory} source={{uri: ICON_EMAIL}}/>
</TouchableOpacity>
<TouchableOpacity style={{justifyContent:'center', alignItems:'center', marginTop:25}}
onPress={() => { this.ShowModalPhoneFunction(true) }}
>
<Image style={styles.inputIconCategory} source={{uri: ICON_PHONE}}/>
</TouchableOpacity>
</View>
</View>
{/* upper portion ends */}
<ScrollView horizontal={true}>
<View style={{flexDirection:'row', flex:1, marginTop:10, marginBottom:10, marginRight:20, marginLeft:10}}>
<TouchableOpacity style={{justifyContent:'center', alignItems:'center', marginRight:10}}
onPress={()=>{this.updateImage(ICON_NOTE, '1')}}
>
<Image style={styles.inputIconCategory} source={{uri: ICON_NOTE}}/>
<Text style={{marginLeft:25, marginTop:5}}>Note</Text>
</TouchableOpacity>
<TouchableOpacity style={{justifyContent:'center', alignItems:'center', marginRight:10}}
onPress={()=>{this.updateImage(ICON_PERSONAL, '8')}}
>
<Image style={styles.inputIconCategory} source={{uri: ICON_PERSONAL}}/>
<Text style={{marginLeft:25, marginTop:5}}>Personal</Text>
</TouchableOpacity>
</View>
</ScrollView>
<TouchableOpacity style={styles.buttonContainerRegister}
onPress=
{()=>{this.submit()}}
>
<Text>Save</Text>
</TouchableOpacity>
<View style = {styles.container}>
<Modal animationType = {"slide"} transparent = {true}
visible = {this.state.ModalVisibleStatus}
onRequestClose = {() =>{ console.log("Modal has been closed.") } }>
{/*All views of Modal*/}
{/*Animation can be slide, slide, none*/}
<View style = {styles.modal}>
<Text style = {styles.text}>Save Email Address</Text>
<View style={styles.inputContainerEmail}>
<Image style={styles.inputIcon} source={{uri: ICON_EMAIL}}/>
<TextInput style={styles.inputs}
placeholder="Email Address"
keyboardType="email-address"
underlineColorAndroid='transparent'
onChangeText={(text) => this.updateValue(text, 'email')}/>
</View>
<View style={{flexDirection:'row'}}>
<TouchableOpacity style={[styles.buttonContainerSave, styles.loginButton]} onPress = {() => {
this.setState({ ModalVisibleStatus:!this.state.ModalVisibleStatus})}}>
<Text style={{color:'#ffff'}}>Save</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.buttonContainerClose, styles.loginButton]} onPress = {() => {
this.setState({ ModalVisibleStatus:!this.state.ModalVisibleStatus})}}>
<Text style={{color:'#ffff'}}>Close</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
</View>
</View>
</ScrollView>
</View>
);
}
}
现在,在这个MakeNote.js类中,我具有Submit函数,可以将表单发布到服务器并启动上一个屏幕NoteMeHome。 B当我这样做时,它会启动NoteMeHome屏幕,但不会刷新,因为未调用用于获取数据的API。因此,每当回到第一个Screen NoteMeHome时,我都需要刷新此类并调用API。
如果有人帮助我找出使用给定代码可以解决此问题的方法,那就太好了。