为什么 React Native 文档建议您在 AsyncStorage 之上使用抽象? [英] Why the React Native docs recommends that you use an abstraction on top of AsyncStorage?

查看:30
本文介绍了为什么 React Native 文档建议您在 AsyncStorage 之上使用抽象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

React Native 文档(https://facebook.github.io/react-native/docs/asyncstorage.html) 说:

The React Native docs (https://facebook.github.io/react-native/docs/asyncstorage.html) says:

建议您在 AsyncStorage 之上使用抽象而不是直接使用 AsyncStorage,因为它在全局范围内运行.

It is recommended that you use an abstraction on top of AsyncStorage instead of AsyncStorage directly for anything more than light usage since it operates globally.

我不明白为什么它推荐我编写抽象只是因为它在全局范围内运行.

I doesn't understood why it recommends I write an abstraction just because it operates globally.

仅将其用于轻量级事物是有意义的,但为什么在全球范围内运营却是一件坏事?

It makes sense to use it only for light things, but why is operating globally a bad thing?

推荐答案

考虑 AsyncStorage 项,例如全局变量,因此每次添加或读取内容时,您都在访问全局变量.这对于 API 基本 URL 之类的内容可能有意义,但对于大多数其他内容,它会开始变得混乱.

Think of AsyncStorage items like global variables, so every time you add something or read something you're accessing a global. This might make sense for something like an API base URL, but for most other things it'll start to get messy.

假设您需要存储有关用户的信息,您可以合理地以他们的姓名开头,因此您将 name 添加到 Async.后来你意识到你想要他们的 DOB,然后可能是他们的 pets 等等.如果您全局创建这些,您还将使用诸如 name 之类的变量名称访问它们 - 在全局上下文中这开始失去意义.此外,你必须写:

Imagine you need to store information about users, you might reasonably start with their name, so you add name to Async. Later you realise you want their DOB, then maybe their pets and so on. If you create these globally you're also going to be accessing them using variable names such as name - which in the global context start to lose meaning. Further, you'd have to write:

AsyncStorage.getItem('name', (err, result) => {
  this.setState({
      name: result
  })
})

整个项目 - 将来如果变量名称 name 发生变化,您必须在所有文件中更新它.

All over your project - in the future if the variable name name changes, you'll have to update it across all files.

相反,您最好编写一个 User 类,该类将提供实例变量(或一些此类变量),然后可以将自己序列化为 Async.此外,如果项目后来得到 API 支持,或者需要更强大的数据库式存储系统,您可以轻松更换存储机制.

Instead you'd be better of writing a User class, which would provide instance variables (or some such), and which could then serialise themselves into Async. Further you could then swap out the storage mechanism with ease if the project later became backed by an API, or required a more powerful database-style storage system.

这篇关于为什么 React Native 文档建议您在 AsyncStorage 之上使用抽象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆