我看到的只是" pera"但是,在{" t pera"。
之前,getStudentName
函数没有得到名字
import React, { Component } from 'react';
import {
Alert,
AppRegistry,
StyleSheet,
Text,
Navigator,
TextInput,
View,
Platform,
TouchableHighlight,
TouchableNativeFeedback,
} from 'react-native';
export class Student extends Component {
getStudentName() {
return fetch('http://192.168.1.14:3005/api/users/57bf7c101a7c1a892f6a19bc')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.name;
})
.catch((error) => {
console.error(error);
})
}
onButtonPress(){
this.props.navigator.push({
id: 'Student'
})
}
render() {
return(
<View style={styles.container}>
<TextInput style={styles.input}
placeholder = "peki"
/>
<Text>
{this.getStudentName}t pera
</Text>
<TouchableHighlight style={styles.button1} onPress={this.getStudentName}>
<Text style={styles.nastavi}>Nastavi</Text>
</TouchableHighlight>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FFFFFF',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
padding: 30
},
input: {
borderBottomColor: 'grey',
borderBottomWidth: 1,
height: 40,
width: 250
},
button1: {
height: 40,
borderRadius: 5,
backgroundColor: '#4a4de7',
width: 250,
marginTop: 20,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center'
},
button2: {
height: 40,
borderRadius: 5,
backgroundColor: 'black',
width: 250,
marginTop: 20,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center'
},
nastavi: {
color: 'white',
fontSize: 15
}
});
module.exports = Student;
答案 0 :(得分:0)
这是因为您的getStudentName()
方法不会返回您期望的字符串,而是一个承诺。您应该从结果更新组件的状态,而不是返回任何内容。
请注意,我已经更换了&#34; this.getStudentName&#34;使用this.state.studentName
,它将返回一个空字符串(在构造函数中定义),直到方法getStudentName()
的promise更新状态。一旦承诺完成并且状态更新,它将自动刷新您的视图以显示学生姓名。
export class Student extends Component {
constructor(props) {
super(props);
this.state = {
studentName: ''
};
}
componentDidMount() {
this.getStudentName();
}
getStudentName() {
var self = this;
return fetch('http://192.168.1.14:3005/api/users/57bf7c101a7c1a892f6a19bc')
.then((response) => response.json())
.then((responseJson) => {
self.setState({
studentName: responseJson.name
});
})
.catch((error) => {
console.error(error);
});
}
onButtonPress(){
this.props.navigator.push({
id: 'Student'
})
}
render() {
return(
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder = "peki" />
<Text>
{this.state.studentName}t pera
</Text>
<TouchableHighlight style={styles.button1} onPress={this.getStudentName.bind(this)}>
<Text style={styles.nastavi}>Nastavi</Text>
</TouchableHighlight>
</View>
);
}