Comments (18)
storage
.load({
key: 'token',
})
.then((data) => {
instance.interceptors.request.use(
(config) => {
config.headers['blade-auth'] = 'bearer ' + data;
},
);
});
from react-native-storage.
另外请问个问题:我用上面的方法存了值,然后退出登陆后(这里做了移除所有的操作,但是没有效果),重新登陆的时候,header里面存的是上一次的token值,这个应该怎么解决呢?
// 退出登录
const handleLogout = () => {
storage.remove('token');
storage.clearMap(); // 清除缓存
navigation.push('Login')
// navigation.navigate('Login')
// console.log('退出登录');
};
from react-native-storage.
建议单独封装token操作,比如
let token;
// 每次需要修改token就调用这个方法
export function saveToken(newToken) {
token = newToken;
storage.save({ key: 'token', data: newToken});
}
export function getToken() {
return token;
}
// 启动时自动读取storage,赋给token
storage.load({ key: 'token' }).then(savedToken => token = savedToken);
instance.interceptors.request.use(
(config) => {
config.headers['blade-auth'] = 'bearer ' + getToken(); // 通过getter方法取
},
);
from react-native-storage.
我独立出这个函数,但是在引用的时候,编译会报错。无法编译通过。
import {storage} from '../storage';
let token = '';
// 每次需要修改token就调用这个方法
export function saveToken(newToken) {
token = newToken;
storage.save({ key: 'token', data: newToken});
}
export function getToken() {
return token;
}
// 启动时自动读取storage,赋给token
storage.load({ key: 'token' }).then(savedToken => token = savedToken);
from react-native-storage.
你这不说是啥错 让人猜吗?
from react-native-storage.
稍等 我把图接上来。
from react-native-storage.
import {getToken} from '../utils/saveToken';
instance.interceptors.request.use(
(config) => {
//console.log('login555555555555', getToken())
config.headers['blade-auth'] = 'bearer ' + getToken(); // 通过getter方法取
},
);
编译报错信息:
E:\project\mobilephonewholesales-app\node_modules\react-native\Libraries\Core\ExceptionsManager.js:76 Error: Requiring module "src\utils\saveToken.js", which threw an exception: TypeError: Cannot read property 'then' of undefined
from react-native-storage.
感觉你的storage.js的导出写的不对
from react-native-storage.
import Storage from 'react-native-storage';
import AsyncStorage from '@react-native-community/async-storage';
import sync from './sync';
let storage;
let defaultExpires = null;
let size = 1000;
const createStorage = () => {
storage = new Storage({
// 最大容量,默认值1000条数据循环存储
size: size,
// 存储引擎:对于RN使用AsyncStorage,对于web使用window.localStorage
// 如果不指定则数据只会保存在内存中,重启后即丢失
storageBackend: AsyncStorage,
// 数据过期时间,默认一整天(1000 * 3600 * 24 毫秒),设为null则永不过期
defaultExpires: defaultExpires,
// 读写时在内存中缓存数据。默认启用。
enableCache: true, // 你可以在构造函数这里就写好sync的方法 // 或是在任何时候,直接对storage.sync进行赋值修改 // 或是写到另一个文件里,这里require引入
sync: sync,
});
};
const initStorage = () => {
if (!storage) {
createStorage();
}
};
const _storage = {
// 使用key来保存数据。这些数据一般是全局独有的,常常需要调用的。
// 除非你手动移除,这些数据会被永久保存,而且默认不会过期。
save(key, obj) {
initStorage();
storage.save({
key: key, // 注意: 请不要在key中使用_下划线符号!
data: obj,
// 如果不指定过期时间,则会使用defaultExpires参数
// 如果设为null,则永不过期
expires: defaultExpires,
});
},
// 取数据
load(key, callBack) {
initStorage();
storage
.load({
key: key,
// autoSync(默认为true)意味着在没有找到数据或数据过期时自动调用相应的sync方法
autoSync: true,
// syncInBackground(默认为true)意味着如果数据过期,
// 在调用sync方法的同时先返回已经过期的数据。
// 设置为false的话,则始终强制返回sync方法提供的最新数据(当然会需要更多等待时间)。
syncInBackground: true,
// 你还可以给sync方法传递额外的参数
syncParams: {
extraFetchOptions: {
// 各种参数
},
someFlag: true,
},
})
.then(ret => {
// 如果找到数据,则在then方法中返回
// 注意:这是异步返回的结果(不了解异步请自行搜索学习)
// 你只能在then这个方法内继续处理ret数据
// 而不能在then以外处理
// 也没有办法“变成”同步返回
// 你也可以使用“看似”同步的async/await语法
callBack && callBack(ret);
return ret;
})
.catch(err => {
//如果没有找到数据且没有sync方法,
//或者有其他异常,则在catch中返回
console.warn(err.message);
switch (err.name) {
case 'NotFoundError':
// TODO
break;
case 'ExpiredError':
// TODO
break;
}
});
},
// 获取某个key下的所有id(仅key-id数据)
getIdsForKey(id, callback) {
initStorage();
storage.getIdsForKey(id).then(ids => {
callback && callback(ids);
});
},
// 获取某个key下的所有数据(仅key-id数据)
getAllDataForKey(key, callback) {
initStorage();
storage.getAllDataForKey(key).then(users => {
callback && callback(users);
});
},
// !! 清除某个key下的所有数据(仅key-id数据)
clearMapForKey(key) {
initStorage();
storage.clearMapForKey(key);
},
// 删除单个数据
remove(key) {
initStorage();
storage.remove({
key: key,
});
},
// !! 清空map,移除所有"key-id"数据(但会保留只有key的数据)
clearMap() {
initStorage();
storage.clearMap();
},
};
export {_storage as storage};
from react-native-storage.
没明白为啥你要把storage的代码几乎再复制一份,还要把promise改成更麻烦更落后的callback?
from react-native-storage.
你改成callback了当然没有then了
from react-native-storage.
import {storage} from './index';
/**
-
sync方法的名字必须和所存数据的key完全相同
-
方法接受的参数为一整个object,所有参数从object中解构取出
-
这里可以使用promise。或是使用普通回调函数,但需要调用resolve或reject
-
@type {{user: ((params))}}
*/
const sync = {
user(params) {
let {
id,
resolve,
reject,
syncParams: {extraFetchOptions, someFlag},
} = params;
fetch('http://www.baidu.com', {
method: 'GET',
body: 'id=' + id,
...extraFetchOptions,
})
.then(response => {
return response.json();
})
.then(json => {
//console.log(json)
if (json && json.user) {
storage.save({
key: 'user',
data: json.user,
});if (someFlag) { // 根据syncParams中的额外参数做对应处理 } // 成功则调用resolve resolve && resolve(json.user); } else { // 失败则调用reject reject && reject(new Error('data parse error')); }
})
.catch(err => {
console.warn(err);
reject && reject(err);
});
},
};
export {sync};
from react-native-storage.
后面这个sync感觉也是根据过期的文档写的?为啥不对着最新的文档写啊?
from react-native-storage.
是这样的,我这里是维护其他同事留下的项目,所以遇到这个问题才来请教的。谢谢帮助。
from react-native-storage.
请问最新的应该怎么弄呢?
from react-native-storage.
看文档啊
from react-native-storage.
from react-native-storage.
好的,我用最新的替换一下以前的试试。谢谢耐心解答。
from react-native-storage.
Related Issues (20)
- syncInBackground: false seems to not work and always leave data undefined HOT 4
- Request - Publish 1.0.1 HOT 2
- 如何同步获取数据? HOT 4
- RN warning when calling getAllDataForKey with many keys
- @react-native-community/async-storage could not be found within the project. HOT 3
- Will I lost data on expire time change? HOT 2
- Please do not use "_" in key!"data" is required in save()!
- "data" is required in save() HOT 3
- ERROR: The modules ['@react-native-community_async-storage', 'react-native-community_async-storage'] point to the same directory in the file system. Each module must have a unique path. HOT 2
- How can I get list of all keys?
- Bundle size doubled in 1.0.1? HOT 1
- database or disk is full HOT 1
- Vulnerabilities during npm install
- Update peer dependencies
- Unhandled JS Exception: [@RNC/AsyncStorage]: NativeModule: AsyncStorage is null. HOT 1
- How to Ignore expiry HOT 6
- I have a issue when i run on iPhone HOT 2
- 有时获取不到刚存的数据 HOT 2
- Warning Expired! Params, when i using 0 in defaultExpires and expires HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from react-native-storage.