我想在设置数据时立即响应asyncstorage 但我似乎找不到办法 这是我的代码
我的listitem onpress => onLearnMore
onLearnMore = (rowData) => {
this.setState({name:rowData.name}),
this.setState({email:rowData.email}),
this.setState({phone:rowData.phone}),
this.setState({street:rowData.location.street}),
this.setState({city:rowData.location.city}),
this.setState({state:rowData.location.state}),
this.setState({postcode:rowData.location.postcode}),
this.saveData();
//this.props.navigation.navigate('Details', { ...rowData });
};
saveData将项目设置为asyncstorage
saveData(){
let data = {
name: this.state.name,
email: this.state.email,
phone: this.state.phone,
street: this.state.street,
city: this.state.city,
state: this.state.state,
postcode: this.state.postcode,
}
AsyncStorage.setItem('data',JSON.stringify(data));
this.previewData();
}
这是我的previewData
previewData = async () =>{
try{
let datachecker = await AsyncStorage.getItem('data');
let parsed = JSON.parse(datachecker);
alert(parsed.name);
}catch(error){
alert(error);
}
}
但是显示设置为asyncstorage的项目的警报不会立即同步。我需要预览两次以获得与设置状态属性相同的结果
更新错误案例 我发现当你设置数据保存到异步存储时它可以立即同步,无论如何都要修复它?
我很抱歉英语不好
答案 0 :(得分:1)
setState在您的第一个方法onEarnMore中是异步的,您应该将所有更新批处理到一个setState并将回调传递给第二个参数。
onLearnMore = (rowData) => {
this.setState({
name: rowData.name,
email: rowData.email,
phone: rowData.phone,
street: rowData.location.street,
city: rowData.location.city,
state: rowData.location.state,
postcode: rowData.location.postcode
}, () => {
// setState second argument is a callback to be invoked
// after updating state finished
// this time you can now call any function that depends on the updated state
this.saveData();
//this.props.navigation.navigate('Details', { ...rowData })
});
};
在你的saveData函数中,AsyncStorage.setItem也是异步的并且返回一个你可以简单地使用.then或await的promise,但如果你使用await,请确保将saveData函数更改为async。
使用.then
AsyncStorage.setItem('data',JSON.stringify(data)).then(this.previewData());
或使用await
async saveData(){
// omitted code
await AsyncStorage.setItem('data',JSON.stringify(data));
this.previewData();
}
答案 1 :(得分:0)
正如名称本身所暗示的那样,它以异步方式存储。为了在完成setItem
时执行某些操作,可以传递回调函数。
查看http://facebook.github.io/react-native/releases/0.49/docs/asyncstorage.html#setitem
您的代码需要
AsyncStorage.setItem('data',JSON.stringify(data), this.previewData.bind(this));