交换机中的异步存储错误未处理的承诺拒绝

问题描述 投票:1回答:2

我是新来的反应原生,现在我有一个问题。我正在尝试使用异步存储将我的数据保存到本地存储中,我正在关注这个tutorial

它工作正常但不在我的开关代码中。这是我的构造函数

 constructor(props) {
    super(props)         
    this.state = {prevBtn: undefined}
    this.onPrevValueChange = this.onPrevValueChange.bind(this);
 }

然后我在didMount中获取该项:

componentDidMount() {
        this.getQuestionnaire();
        AsyncStorage.getItem('prevBtn').then((value) => this.setState({ 'prevBtn': value }));
    }

更改时设置值:

onPrevValueChange = (value) =>  {
    AsyncStorage.setItem('prevBtn', value);
    this.setState({ prevBtn: value  });
}

和渲染方法:

render(){
    const {}
    return(
        <Switch 
             value={prevBtn}
             backgroundActive={'red'}
             onValueChange={this.onPrevValueChange}  
        /> 
    );
}

有人可以帮忙吗?

react-native
2个回答
0
投票

setStatecomponentDidMount中的问题,当你使用单引号设置prevBtn的值时,所以它的行为类似于String而不是state,请使用如下:

componentDidMount() {
        this.getQuestionnaire();
        AsyncStorage.getItem('prevBtn').then((value) => this.setState({ prevBtn: value }));
    }

render你直接使用prevBtn,用它作为this.state.prevBtn

render(){
    const {}
    return(
        <Switch 
             value={this.state.prevBtn}
             backgroundActive={'red'}
             onValueChange={this.onPrevValueChange}  
        /> 
    );
}

0
投票

您需要将componentDidMount更改为:

请注意,AsyncStorage.getItem始终返回一个字符串,您必须在使用它之前将其转换为布尔值。正如另一位评论者指出的那样,你不能在国家财产周围引用。

componentDidMount() {
  this.getQuestionnaire();
  AsyncStorage.getItem('prevBtn').then((value) => {
    value === 'true' 
      ? this.setState({ prevBtn: true })
      : this.setState({ prevBtn: false })
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.