我想在 AsyncStorage 块中使用 setState ,但是有一个错误: undefined不是对象(评估'this.setState')。
boolean isPasswordValid(String encPass, String rawPass, Object salt) throws DataAccessException
感谢任何帮助。
答案 0 :(得分:4)
这是一个具有约束力的问题。请尝试以下方法:
componentDidMount() {
AsyncStorage.getItem(this.props.data.type, (errs,result) => {
if (!errs) {
if (result !== null) {
this.setState({activeID:result});
}
}
})
}
这样做的原因是用function
说明符声明的函数会创建自己的上下文,也就是说this
的值不是组件的实例。但是“胖箭头”功能不会创建新的上下文,因此您可以使用内部的所有方法。您也可以bind
函数来保持上下文,但在这种情况下,我认为这个解决方案更清晰。
答案 1 :(得分:0)
我找到了另一个解决方案,但 martinarroyo 的答案要清晰得多。
componentDidMount() {
this._loadInitialState().done();
}
async _loadInitialState(){
try{
var value=await AsyncStorage.getItem(this.props.data.type);
if(value!=null){
this._saveActiveID(value);
}
} catch(error){
}
}
_saveActiveID(id) {
this.setState({activeID: id});
}