我正在尝试将呼叫清单呈现给我的呼叫应用程序,但遇到了一些麻烦(“找不到变量:人”)。 该组件将仅呈现联系人全名和联系人电话号码。
这是我的代码:
import {View, Text} from "react-native";
import Contacts from 'react-native-contacts';
class ContactScreen extends Component {
constructor(props) {
super(props);
this.state = {
ContactsList: ''
};
}
componentDidMount(){
Contacts.getAll((ContactsList) => {this.setState({ContactsList})})
}
render() {
return (
<View style={{justifyContent: 'center'}}>
this.state.ContactsList.map((person) =>
<Text>person.givenName + person.familyName</Text>
<Text>person.phoneNumbers[0].number</Text>
)
</View>
)
}
}
答案 0 :(得分:0)
将构造函数更改为具有
this.state = {
ContactsList: []
}
然后,将您的渲染功能更改为:
this.state.ContactsList.map((person, i) =>
<View key={i}>
<Text>{person.givenName + person.familyName}</Text>
<Text>{person.phoneNumbers[0].number}</Text>
</View>
)
答案 1 :(得分:0)
Just fixing some syntax below.
import {View, Text} from "react-native";
import Contacts from 'react-native-contacts';
class ContactScreen extends Component {
constructor(props) {
super(props);
this.state = {
ContactsList: ''
};
}
componentDidMount(){
Contacts.getAll((ContactsList) => {this.setState({ContactsList})})
}
render() {
const { ContactsList } = this.state
let contacts = []
if (ContactsList) {
ContactsList.map((person, i) => {
contacts.push(
<View key={i}>
<Text>{person.givenName + person.familyName}</Text>
<Text>{person.phoneNumbers[0].number}</Text>
<View>
)
}
}
return (
<View style={{justifyContent: 'center'}}>
{contacts}
</View>
)
}
}
答案 2 :(得分:0)
您应该阅读有关React.Component Lifecycle
简而言之,组件将在渲染前后经历一些步骤。其中之一是您在代码中使用的componentDidMount()。问题在于,componentDidMount()在render()方法之后正在运行。这就是为什么您的联系人列表未初始化的原因。如果要在渲染组件之前创建列表,则应使用componentWillMount()。为了了解流程,我建议您从每个生命周期方法中调用console.log(“ METHOD NAME HERE”),以便您可以看到确切的流程。