2017-05-03 80 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。所以,國家不會到達 {...}? –