React Native - AsyncStorage 屏幕在加载时更新内容



看过其他解决方案,但在我看来它们似乎并不好。

我有一个实用程序.js文件:

const setItem = async (value) => {
if (!value) return;
AsyncStorage.setItem('@my_key', value);
};
const getItem = async () => {
var val = await AsyncStorage.getItem('@my_key');
return val;
};

所有用户的输入都通过 Screen1 上的代码保存在 AsyncStorage 中:

Utilities.setItem('value')

保存数据后,我们可以转到 Screen2 通过放入 ComponentDidMount 方法中的 getItem(( 方法读取 AsyncStorage:

componentDidMount = async () => {
let asyncValue = await Utilities.getItem();
let objFromAsyncValue = JSON.parse(asyncValue);
this.setState({
storage: objFromAsyncValue
})
}

如果我第一次打开 Screen2,一切正常 - 所有保存的数据都显示出来,但返回并为 AsyncStorage obj 添加其他值不会在 Screen2 上更新 - 但 asyncstorage 添加了更多项目。

到目前为止已经尝试了触发方法:

this.forceUpdate() 

并检查加载时是否已触发事件 onDidFocus:

<NavigationEvents onDidFocus={ alert('Scren refreshed')} />

我知道组件渲染是基于状态的,但在我的实例中,我没有要更新的状态,只有 AsyncStorage 无状态对象。

如何刷新屏幕和/或仅读取 AsyncStorage 对象的更新内容?

我认为您假设每次聚焦时都会安装Screen2。这可能不一定是真的。您应该做的是将getItem调用移动到另一个方法中并将其调用onWillFocus

喜欢这个

onFocus = async () => {
let asyncValue = await Utilities.getItem();
let objFromAsyncValue = JSON.parse(asyncValue);
this.setState({
storage: objFromAsyncValue
})
}

然后

<NavigationEvents onDidFocus={ alert('Scren refreshed')} onWillFocus={this.onFocus}/>

在您的情况下,我会使用一个上下文,其中您的提供者是用户键入并保存到异步存储的内容,消费者将是屏幕 2。这样,您只需访问屏幕 1 上的异步存储,屏幕 2 将始终保持最新状态,以显示屏幕上键入和保存的任何内容

请参阅:https://reactjs.org/docs/context.html

最新更新