2016-04-25 35 views
3

ReactとReact Nativeの新機能だと言ってこれを前に説明しましょう。React Nativeでデータが変更された後にコンポーネントが更新されない

Reactネイティブモジュール(https://github.com/rt2zz/react-native-contacts)を使用して電話の連絡先リストにアクセスしていますが、その連絡先をListviewに表示しようとしています。しかし、私のアプリをエミュレータ(Genymotion)で実行した後、私は連絡先配列に対して行ったデータ変更に基づいてListviewを更新しません。

ここに私のindex.android.jsです:

import React, {AppRegistry, Component, StyleSheet, TouchableOpacity, Text, 

View, ListView} from 'react-native'; 

var l_mContacts = require('react-native-contacts'); 

var l_cAllContacts = [ ]; 

var newPerson = { 
    familyName: "Nietzsche", 
    givenName: "Friedrich", 
    emailAddresses: [{ 
    label: "work", 
    email: "[email protected]", 
    number: "123456789" 
    }] 
}; //sample person 

    l_mContacts.addContact(newPerson, (err, contacts) => { 
    if(err && err.type === 'permissionDenied'){ 
    alert("error"); 
    } else { 
    } 

    }) 



    l_mContacts.getAll((err, contacts) => { 
    if(err && err.type === 'permissionDenied'){ 
     alert("error"); 
    } else { 
     l_cAllContacts = contacts; //data changes here 
     alert(contacts); //I can successfully see the sample contact I added here 
    } 
    }); 

class ReactNativeTest extends Component { 
    constructor(props){ 
    super(props) 
    var ds = new ListView.DataSource({ 
     rowHasChanged: (r1, r2) => r1 !== r2, 
     enableEmptySections: true 
    }) 
    this.state = { 
     contactDataSource: ds.cloneWithRows(l_cAllContacts) 
    } 
    } 
    render() { 
    return (
     <View> 
      <ListView 
      dataSource={this.state.contactDataSource} 
      renderRow={(contact) => {return this._renderContactRow(contact)}} 
      /> 
     </View> 
    ); 
    } 

    _renderContactRow(contact){ 
    return (
     <View> 
     <Text>{contact ? contact.givenName : "none"}</Text> 
     </View> 
    ) 
    } 
} 

AppRegistry.registerComponent('ReactNativeTest',() => ReactNativeTest); 

私が間違ってやっている任意のアイデア?私が "l_mContacts.getAll"関数内の "contacts"変数に警告すると、私は期待した結果を見るが、コンポーネントを更新しない。私は助けていただきありがとうございます。

答えて

2

問題は、あなたのやり方で反応が無視されることです。 Reactのコンポーネントがプログラマの観点からどのように機能するかを簡単に説明しましょう。最初に1回レンダリングされ、状態またはその小道具が変更された場合に再レンダリングが発生します。

あなたがしていることは、情報がファイルの読み込みに表示されていることです。これは一度は動作しますが、変更された情報や何らかの形でコールバックに巻き込まれた情報を取得する可能性はありません。できることはコンストラクタでgetAllメソッドを実行し、コールバック内でsetStateを使用してcontactDataSource状態を再度設定することです。

+1

ありがとうございます、私はあなたの助言をしてそれを理解しました。私は "componentDidMount"関数を使う必要がありました。 – Ryan

関連する問題