如何使用本机反应在 AsyncStorage 块中设置状态?

mag*_*527 4 ios react-native

我想的setStateAsyncStorage块,但有一个错误:未定义没有(评估“this.setState”)的对象

constructor(props){
    super(props);
    this.state={
        activeID:this.props.data.channel[0].id
    };
}

componentDidMount() {
    AsyncStorage.getItem(this.props.data.type,function(errs,result){
        if (!errs) {
            if (result !== null) {
                this.setState({activeID:result});
            }
        }
    });
}

_buttonPressed = (id,name,index) => {
    this.setState({activeID:id});

    AsyncStorage.setItem(this.props.data.type,id,function(errs){
     if (errs) {
       console.log('error');
     }
     if (!errs) {
       console.log('succeed');
     }
 });
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激,谢谢。

mar*_*oyo 6

这是一个有约束力的问题。请尝试以下操作:

componentDidMount() {
    AsyncStorage.getItem(this.props.data.type, (errs,result) => {
        if (!errs) {
            if (result !== null) {
                this.setState({activeID:result});
            }
         }
    })
 }
Run Code Online (Sandbox Code Playgroud)

这样做的原因是使用说明function符声明的函数会创建自己的上下文,即 的值this不是您组件的实例。但是“胖箭头”函数不会创建新的上下文,因此您可以使用其中的所有方法。您也可以使用bind该函数来保留上下文,但在这种情况下,我认为此解决方案更简洁。