gpt4 book ai didi

react-native - React Native - 观察 AsyncStorage 值的变化?

转载 作者:行者123 更新时间:2023-12-04 17:27:58 25 4
gpt4 key购买 nike

有没有办法订阅 AsyncStorage值(value)变化?我在一个地方有一个设置保存在 AsyncStorage在应用程序中,这会影响其他所有屏幕。我需要观察该值,以便可以更新所有屏幕。我试过 getValue方法但它似乎最初只获取一个值,并且不会在更改时更新。

最佳答案

我通过构建一个同步到 AsyncStorage 的 React Context 在我的应用程序中解决了这个问题。
在你的情况下,你可以有一个项目,例如 appSettings .这将是一个字符串化的 JSON 对象,其中包含您的所有应用设置。

const AppSettingsContext = React.createContext({})

const AppSettingsContextProvider = ({children}) => {
const [appSettingsInitialized, setAppSettingsInitialized] = useState(false)
const [appSettings, setAppSettings] = useState({}) // could use some default values instead of empty object

// On mount, get the current value of `appSettings` in AsyncStorage
useEffect(() => {
AsyncStorage
.getItem('appSettings')
.then(data => {
// If data is returned, the storage item existed already and we set the appSettings state to that.
if (data) {
setAppSettings(JSON.parse(data))
}
// If data is null, the appSettings keeps the default value (in this case an empty object)/

// We set appSettingsInitialized to true to signal that we have successfully retrieved the initial values.
setAppSettingsInitialized(true)
})
}, [])

// setSettings sets the local state and AsyncStorage
const setSettings = (key, value) => {
const mergedSettings = {
...appSettings,
[key]: value
}
// First, merge the current state with the new value
setAppSettings(mergedSettings)

// Then update the AsyncStorage item
AsyncStorage.setItem('appSettings', JSON.stringify(mergedSettings))
}

return (
<AppSettingsContext.Provider value={{
appSettings,
appSettingsInitialized,
setSettings,
}}>
{children}
</AppSettingsContext.Provider>
)
}
(请注意,这是一个非常基本的版本,没有错误处理)
然后将您的应用程序包装在 AppSettingsContextProvider 中
const App = () => (
<AppSettingsContextProvider>
{/* Other components */}
</AppSettingsContextProvider>
)
然后使用来自任何子组件的上下文:
const SomeChildComponent = () => {
const { appSettingsInitialized, appSettings } = useContext(AppSettingsContext)

// For example: wait until initial appSettings have been retrieved AsyncStorage,
// then use some value that you expect to be present in your business logic.
// In this case, setAppTheme would set the them color for the whole app, using a
// `theme` setting saved by the user.
useEffect(() => {
if (appSettingsInitialized) {
setAppTheme(appSettings.theme)
}
}, [appSettingsInitialized])

// Update settings like this for example
const updateThemeSetting = (newThemeValue) => {
setSettings('theme', newThemeValue) // eg 'dark', 'light', etc
}
}

关于react-native - React Native - 观察 AsyncStorage 值的变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62177966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com