2017-07-03 43 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 }); 
    }) 
    }