2017-05-03 32 views
0

我的英语不好,但我会尝试解释我的问题。用组件react-native-contacts获取联系人的道具

我已经获得了React Native Android中的联系人的propName名称。我装的成分反应本土的接触和使用的下一个代码的console.log打印()的唯一联系人的姓名:

import React, { Component } from 'react'; 
... 
import Contacts from 'react-native-contacts'; 
... 
class myComponent extends Component { 
... 
render() { 
    Contacts.getAll((err, contacts) => { 
    console.log(typeof err + err); 
    if(err === 'denied'){ 
    // x.x 
    } else { 
    console.log(contacts); 
    console.log("Nombre de contacto: " + contacts[0].givenName); 
    } 
    }) 
    return (
    <Container> 
    ... 
    <View> 
     <Text>{}</Text> 
    </View> 
    </Container> 
); 
} 
} 

所以,我需要在{}打印的联系人的姓名。我试图把它看作是一个平面物体。谢谢!

回答

0

你应该将你的代码进行渲染和使用状态的

componentWillMount() { 
    Contacts.getAll((err, contacts) => { 
    console.log(typeof err + err); 
    if(err === 'denied'){ 
    // x.x 
    } else { 
     console.log(contacts); 
     console.log("Nombre de contacto: " + contacts[0].givenName); 
     this.setState({contacts}); 
    } 
    }) 
} 

那么你的渲染()会像

<View> 
    <Text>{this.state.contacts[0].givenName}</Text> 
</View> 
+0

谢谢您的回答。我尝试了你的提议,但运行该项目显示:无法读取未定义的属性'0'。 –

+0

听起来就像你试图在Contacts.getAll()返回之前渲染它,state.contacts的空检查应该工作吗? –

+0

好吧,如果检查state.contacts == null,在控制台中显示false。所以,国家不会到达 {...}? –