React Native:ComponentDidMount不会更新AsyncStorage.getItem

时间:2019-03-08 17:20:38

标签: react-native push-notification state asyncstorage

在我的应用程序中,我有一个类(NotificationScreen)可以更改发生通知之前的时间(之前5分钟,10,20等)。它将AsyncStorage与setItem和getItem结合使用的方式如下:

componentDidMount更新状态/文本以反映所选择的时间。它会获取该项目,如果它最初为null(用户首次使用该应用时),则将其设置为30分钟之前,如果不是,则它将获取所选择的值。

componentDidMount = () =>{
    AsyncStorage.getItem(this.accessKeyTime).then(value => {
      if(value == null){
        this.setState({ timeSelected: '30'})
        console.warn("time set to 30")
      }
      else {
        this.setState({ timeSelected: value})
        console.warn("time set to " + value)
      }
    });
  }

这是在模式选择器中,当用户选择时间并按“完成”时,AsyncStorage会将状态设置为任何“选项”。

onSubmit={(option) => {
            AsyncStorage.setItem(this.accessKeyTime, option).then(() => {
              this.setState({ timeSelected: option});
            }).then(console.warn("time set to " + option));
          }}

在另一个类[Bell.js](这是ANOTHER类调用的组件)中,在其中进行通知的地方,我有一个componentDidMount来更改timeSelected的状态。因此,当用户想要更改在收到通知之前的时间时,他们可以从NotificationScreen页面更改时间,并且当用户点击bell组件时,它应该反映回Bell.js。

componentDidMount = () =>{

    this.setState({
        fireDate:this.props.fireDate,
        LaunchStatus: this.props.LaunchStatus,
        ID: this.props.ID,
        TitleName: this.props.TitleName,
    });

    AsyncStorage.getItem(this.accessKeyTime).then(value => {
      if(value == null){
        this.setState({ timeSelected: 30*60000}) //Changes to milliseconds
        this.setState({timeShow: 30})
        console.warn("time set to 30")

      }
      else {
        this.setState({ timeSelected: parseInt(value,10)*60000}) // is string at first but changes to int for notification firedate
        this.setState({timeShow: value})
        console.warn("time set to " + value)
      }
    });

  }

错误:  当我在NotificationScreen中更改时间时,在Bell.js中它不会更改,直到我关闭(刷新)应用程序并将其打开。我试过的是将Bell.js中的getItem放置在Bell ICON的onPress上,这种方式可行,但是我必须点按两次响铃图标才能将其更新为正确的图标。

0 个答案:

没有答案
相关问题