同じ状態名の複数のコンポーネント、他のコンポーネントに影響を与えずに1つのコンポーネントの1つの状態を変更するにはどうすればよいですか?

ノエデュラン

私のreactNativeプログラムには、APIから呼び出されるすべてのアイテム/リストに対して呼び出されるコンポーネント(Bell)があります。ベルは、プレス時に通知を行う(およびキャンセルする)ために使用され、ベルがオンになっているかどうかを判断するための状態(isBellActive)を作成しました。そうである場合、isBellActiveはtrueであり、そうでない場合はfalseです。asyncStorageを介してデータを保存しています。

問題は、1つのベル(1つのアイテム/リスト)の状態を変更してからアプリを閉じて再起動すると、そのベルからの状態変更が他のすべてのベルコンポーネントのisBellActive状態に影響することです。状態が(すべて同じ名前を共有している場合でも)1つの特定のアイテム/リストに対して保持されるようにする方法

ベルコンポーネントクラス

export default class Bell extends React.Component {
  constructor(props) {
    super(props);  
    this.state = {
      isBellActive:  null,

    };
  }

  componentDidMount = ()=>{
    AsyncStorage.getItem('isBellActive').then(value => this.setState({ isBellActive: JSON.parse(value) }));
  }

  setTrue(){
    AsyncStorage.setItem('isBellActive', JSON.stringify(true)).then(() => {
      this.setState({ isBellActive: true});
    });
  }

  setFalse(){
    AsyncStorage.setItem('isBellActive', JSON.stringify(false)).then(() => {
      this.setState({ isBellActive: false});
    });
  }

  render() {
     return (
      <Ionicons

        name={this.state.isBellActive? "md-notifications":"md-notifications-off"}
        color={"white"}
        size={30}
        style={styles.NotifIcon}
        onPress={() => {       
            Vibration.vibrate()
             if(this.state.isBellActive == false){             
                  PushNotificationIOS.scheduleLocalNotification({
                    userInfo:{
                      ID: this.state.ID
                    },
                    alertTitle: "Launching Soon:",
                    alertBody: this.state.alertBody,
                    fireDate: this.state.fireDate // in 30 mins
                    });
                    this.setTrue()
                    this.setState({Key:true})
                  }
                  else if(this.state.isBellActive != false){
                    PushNotificationIOS.cancelLocalNotifications({ID:this.state.ID});
                    this.setFalse()
                  }
                }
            }
         }}
       />
    );
  }
}

コンポーネントを呼び出すクラス

export default class LaunchingScreen extends React.Component{
 let launches = this.state.dataSource.map((item, key) => {
   ..
   <View>
    ..
    <Bell />
    ..
   </View>
     ..
  }
}

UPDATEこれはコンポーネントを呼び出すクラスにあり、すべての情報を含むJSONを取得します。

componentDidMount(){
    return fetch("https://launchlibrary.net/1.4/launch/next/20")
      .then(response => response.json())
      .then(responseJson => {
        this.setState({
          isLoading: false,
          dataSource: responseJson.launches
        }); 
      })
      .catch(error => {
        console.log(error);
      });
  }

アイテムの写真とそれはベルです

プラスン

共有されているAPIからの応答によると、そのidプロパティは一意であるように見えます。そのプロパティを使用しkeyBellコンポーネントを一意に定義しそれを使用してkeyからデータを保存/取得できますAsyncStorage次のコードスニペットを検討してください

LaunchingScreen変更して追加key={item.id}

export default class LaunchingScreen extends React.Component{
  let launches = this.state.dataSource.map((item, key) => {
    ..
    <View>
    ..
    <Bell key={item.id}/>
    ..
    </View>
    ..
  }
}

今ではBellコンポーネントからデータにアクセスするためにキープロパティを使用しますAsyncStorage

export default class Bell extends React.Component {
  constructor(props) {
    super(props);  
    this.state = {
      isBellActive:  null
    };
    this.accessKey = `${props.key}-isBellActive`;
  }

  componentDidMount = ()=>{
    AsyncStorage.getItem(this.accessKey).then(value => this.setState({ isBellActive: JSON.parse(value) }));
  }

  setTrue(){
    AsyncStorage.setItem(this.accessKey, JSON.stringify(true)).then(() => {
      this.setState({ isBellActive: true});
    });
  }

  setFalse(){
    AsyncStorage.setItem(this.accessKey, JSON.stringify(false)).then(() => {
      this.setState({ isBellActive: false});
    });
  }

  render() {
     return (
      <Ionicons

        name={this.state.isBellActive? "md-notifications":"md-notifications-off"}
        color={"white"}
        size={30}
        style={styles.NotifIcon}
        onPress={() => {       
            Vibration.vibrate()
             if(this.state.isBellActive == false){             
                  PushNotificationIOS.scheduleLocalNotification({
                    userInfo:{
                      ID: this.state.ID
                    },
                    alertTitle: "Launching Soon:",
                    alertBody: this.state.alertBody,
                    fireDate: this.state.fireDate // in 30 mins
                    });
                    this.setTrue()
                    this.setState({Key:true})
                  }
                  else if(this.state.isBellActive != false){
                    PushNotificationIOS.cancelLocalNotifications({ID:this.state.ID});
                    this.setFalse()
                  }
                }
            }
         }}
       />
    );
  }
}

上記のコンポーネントでは、最初にthis.accessKey = ${props.key}-isBellActive;を使用してアクセスキーを決定します次に、のthis.accessKey代わりにを使用しますisBellActive

これがお役に立てば幸いです!!!

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Related 関連記事

ホットタグ

アーカイブ