我正在尝试向服务器发出GET请求以检索JSON形式的产品列表。然后,我想将数据放入AsyncStorage,以便可以在视图中显示产品。正确的方法是什么?
我研究了什么:
在https://facebook.github.io/react-native/docs/asyncstorage.html上,在示例中,他们解释了如何从AsyncStorage检索值,而不是设置并同时检索它
是)我有的:
componentDidMount () {
this.fetchProducts()
this._loadInitialState().done();
}
_loadInitialState = async () => {
try {
var value = await AsyncStorage.getItem('products')
if (value != null) {
this.setState({products: value});
}
} catch (error) {
console.log("error setting product list");
}
}
fetchProducts() {
fetch("http://localhost:3000/products",{
method: "GET",
headers: {
'Content-Type': 'application/json'
},
})
.then((response) => (response.json()))
.then((data) => setProductList(data));
}
setProductList(json_data) {
Async.setItem('products': json_data);
}
render() {
console.log(this.state.products)
//render view
}
Run Code Online (Sandbox Code Playgroud)
-> this.state.products为null,我肯定知道服务器通过curl返回了响应。我是本机反应的新手,所以也许我的想法不对了。有人可以解释执行此操作的正确方法还是建议其他方法?
我所知道的 异步存储是一个键值存储,应用可以在其中放置其数据。可以将这些数据从异步存储放入对象的状态,并且视图将相应地更新
我现在正在修改使用JSON Web令牌进行身份验证,在本机应用程序和express/passport-jwt服务器之间进行身份验证.
我可以检查从应用程序到服务器的凭据/登录没有问题,并且当密钥返回时server to app,我可以console.log(response.token)在应用程序控制台上.
然后我保存它 AsyncStorage.setItem('JWT_Key', response.token)
我的问题是,当我使用console.log(AsyncStorage.getItem('JWT_Key'))它返回时返回它[Object] [Object]
我似乎无法在文档中看到任何内容,有人可以告诉我我错过了什么吗?
如何在react-native中使用AsyncStorage保存一个Items数组?因此,每次在列表中添加其他联系人时,它都会不断添加而不是重写
码:
saveContacts = ()=> {
try {
let con = {
roomId: this.state.roomId,
nickname: this.state.nickname,
}
AsyncStorage.setItem('contacts', JSON.stringify(con));
}catch(error) {
alert(error)
}
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试进行身份验证,因此我的 App.js:
import React, { Component } from "react";
import { AsyncStorage } from "react-native";
import Router from "./Router";
import ScanForm from "./components/ScanForm";
console.disableYellowBox = true;
class App extends Component {
state = {
isLoggedIn: false
};
componentWillMount() {
const temp = AsyncStorage.getItem("operator");
console.log(temp);
if (temp !== undefined) {
this.setState({ isLoggedIn: true });
}
}
render() {
if (this.state.isLoggedIn) {
return <ScanForm />;
} else {
return <Router />;
}
}
}
export default App;
Run Code Online (Sandbox Code Playgroud)
因此,如果这是用户第一次打开应用程序,operator则为 null 或未定义(我尝试了两者但没有结果)-(然后在用户登录后, …
我有一个小的 React Native 组件,我尝试通过从本地存储(AsyncStorage)读取值来初始化状态。但是当我从构造函数调用外部方法时,我的状态值 未定义。
这是我的代码的一部分:
constructor(props) {
super(props);
this.state = {
languageChecked: I18n.locale,
anonymityChecked: this.pickLocalKey('anonymity', true),
locationChecked: this.pickLocalKey('location', false),
notificationChecked: this.pickLocalKey('notification', false),
statisticsChecked: this.pickLocalKey('statistics', false),
};
console.log("STATE: " + this.state.anonymityChecked); // UNDEFINED
}
pickLocalKey(key, defaultValue) {
AsyncStorage.getItem(key).then((value) => {
const item = (value !== null && value !== undefined) ? value : defaultValue;
console.log(item);
return item;
});
}
Run Code Online (Sandbox Code Playgroud)
有谁知道如何解决这个问题?先感谢您
我正在学习typescript并且React-Native我想使用AsyncStorage图书馆。从存储读取值后设置状态时,我遇到了这个问题:
常量值:字符串| null 类型为 'string | 的参数 null' 不能分配给'SetStateAction<never[]>' 类型的参数。类型“null”不可分配给类型“SetStateAction<never[]>”
该应用程序显示了价值,但我想了解如何解决问题。我想我必须将 a 分配type给useState,但不知道如何分配SetStateAction类型。
如何设置类型来useState解决这个问题?
这是示例代码:
import React, {useEffect, useState} from 'react';
import {Text, View} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
const App = () => {
const [value, setValue] = useState([]);
async function saveValue(key: string, value: string) {
await AsyncStorage.setItem(key, value);
}
async function readValue(key: string) {
const value = await AsyncStorage.getItem(key);
setValue(value);
}
useEffect(() => …Run Code Online (Sandbox Code Playgroud) 我有App.js文件,它是我的应用程序的根目录(ios和android都对其引用)。
在调用render方法AsyncStorage之前,我有一个需要保存的值app.js。
问题在于,async现在太晚了,我无法获得那个价值。
class App extends React.Component {
constructor(props) {
super(props);
this.init()
}
async init() {
try {
const value = await AsyncStorage.getItem('@myPoorValue:key');
if (value !== null){
...
}
} catch (error) {}
}
}
...
render (...
Run Code Online (Sandbox Code Playgroud)
我希望我能很好地解释我的问题。
我知道没有办法使它同步(我想这样),但是不知道在这种情况下该怎么做。
为了更好地解释它,我使用了I18n手动设置I18n.locale为某些值的方式,其他组件在手动设置之前获得了默认值。
请注意,我也使用redux,并将选定的值传递给它。
AsyncStorage无法保留数据,我用完了保存一组对象并用列表中的新条目更新它们的选项。请帮忙
我将这个库用于我的应用程序介绍:https : //github.com/Jacse/react-native-app-intro-slider
这是我的代码:
import React from 'react';
import { StyleSheet, View, Text } from 'react-native';
import {Container} from 'native-base';
import AppIntroSlider from 'react-native-app-intro-slider';
import { AntDesign } from '../../styles/variables/Icons';
export default class TestView extends React.Component {
constructor(props) {
super(props);
this.state = {
showRealApp: false,
//To show the main page of the app
};
}
_onDone = () => {
// After user finished the intro slides. Show real app through
// navigation or simply by controlling state
this.setState({ …Run Code Online (Sandbox Code Playgroud) 与React-Native项目合作,我决定根据官方文档为 AsyncStorage 编写一个允许使用对象的小型服务
import {AsyncStorage} from "react-native-web";
export async function getUserFromStore() {
try {
const user = await AsyncStorage.getItem('userData');
return JSON.parse(user);
} catch (error) {
console.log('ERROR. Trying to get user data to store, got ', error)
}
}
export async function saveUserToStore(data) {
await AsyncStorage.setItem(
'userData',
JSON.stringify(data),
(error) => {
console.log('ERROR. Trying to set user data to store, got ', error)
}
);
}
Run Code Online (Sandbox Code Playgroud)
我在登录期间设置用户数据对象。我正在进入主要组件以决定要呈现的内容
const AppStackScreen = () => (
<AppStack.Navigator>
<AppStack.Screen name="Tabbed" component={TabsScreenNavigationScreen} /> …Run Code Online (Sandbox Code Playgroud) 我有一个反应本机应用程序,我在其中进行一些身份验证。
我有以下代码,用于检查令牌是否未过期且可用。
export const isLogged = () => {
AsyncStorage.getItem('@token')
.then( token => {
if (typeof token !== 'undefined') {
if (tokenExpired(token)) {
return false
}
return true
}
return false
} )
.catch( error => {
return false
} )
}
Run Code Online (Sandbox Code Playgroud)
但在我的代码中,如果我这样做:
let isUserLogged = isLogged()
console.log(isUserLogged) // -> returns undefined, but should return true because the token is there and its not expired.
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么会这样,我做错了什么?
asyncstorage ×11
react-native ×11
javascript ×6
reactjs ×5
arrays ×1
async-await ×1
items ×1
react-redux ×1
types ×1
typescript ×1