2017-07-03 46 views
0

我存储如果复选框被选中或不使用AsyncStorage。当我重新加载应用程序时,我从日志中看到异步变量内存储了正确的信息。但是,它在componentWillMount之后加载。因此,该复选框不会显示为已选中状态,因为它应该是。React Native - 异步存储信息被提取后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在构造函数中没有什么区别。

回答

0

谢谢你的回答。我非常确定等待会有效,但我在得到答案之前解决了问题。我所做的是在开始时将状态设置为false,然后在getCache中更新它。这样,从本地电话存储获取信息后,它将始终设置。

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); 
    } 
    } 
0

您使用异步 - 等待,但您不等待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) 
    } 
0

异步函数的返回值是一个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 }); 
    }) 
    }