React Native - 在 componentWillMount() 之后提取异步存储信息

React Native - Async storage information is extracted after componentWillMount()

我正在使用 AsyncStorage 存储复选框是否被选中。当我重新加载应用程序时,我从日志中看到异步变量中存储了正确的信息。但是,它是在 componentWillMount 之后加载的。因此,该复选框未显示为已选中,但它应该是选中的。

我认为一个好的解决方法是更改​​异步函数内的复选框属性。你认为这是一个好的解决方案吗?对于显示正确的复选框值,您还有其他建议吗?

我的代码:

constructor(props) {
    super(props)
    this.state = {isChecked: false}
    this.switchStatus = this.switchStatus.bind(this)
  }

  async getCache(key) {
    try {
      const status = await AsyncStorage.getItem(key);
      if (status == null)
        status = false
      console.log("my async status is " + status)
      return status
    } catch(error) {
      console.log("error", e)
    }
  }

  componentWillMount(){
    // key string depends on the object selected to be checked
    const key = "status_" + this.props.data.id.toString()
    this.getCache = this.getCache.bind(this)
    this.setState({isChecked: (this.getCache(key) == 'true')})
    console.log("my state is" + this.state.isChecked)
  }

  switchStatus () {
    const newStatus = this.state.isChecked == false ? true : false
    AsyncStorage.setItem("status_" + this.props.data.id.toString(), newStatus.toString());
    console.log("hi my status is " + newStatus)
    this.setState({isChecked: newStatus})
  }

  render({ data, onPress} = this.props) {
    const {id, title, checked} = data
    return (
      <ListItem button onPress={onPress}>
        <CheckBox
          style={{padding: 1}}
          onPress={(this.switchStatus}
          checked={this.state.isChecked}
        />
        <Body>
          <Text>{title}</Text>
        </Body>
        <Right>
          <Icon name="arrow-forward" />
        </Right>
      </ListItem>
    )
  }

如果我在构造函数中将所有内容都放在 componentWillMount 中,没有区别。

您使用了 async - await,但您并未在 componentWillMount() 中等待您的方法。试试这个:

componentWillMount(){
    // key string depends on the object selected to be checked
    const key = "status_" + this.props.data.id.toString()
    this.getCache =  await this.getCache.bind(this)   // <-- Missed await
    this.setState({isChecked: (this.getCache(key) == 'true')})
    console.log("my state is" + this.state.isChecked)
  }

异步函数的return值是一个Promise对象。所以你必须使用 then 来访问 getCache 的解析值。将您的代码更改为以下内容,它应该可以工作。

  componentWillMount(){
    // key string depends on the object selected to be checked
    const key = "status_" + this.props.data.id.toString();
    this.getCache(key).then(status => {
      this.setState({ isChecked: status === true });
    })
  }

感谢您的回答。我很确定 await 也会工作,但我在得到答案之前解决了问题。我所做的是一开始将状态设置为false,然后在getCache中更新它。这样,在从本地phone存储中获取信息后,它将始终被设置。

async getCache(key) {
    try {
      let status = await AsyncStorage.getItem(key);
      if (status == null) {
        status = false
      }
      this.setState({ isChecked: (status == 'true') })
    } catch(e) {
      console.log("error", e);
    }
  }