[英]react native state not changing
我想使用钩子将字符串从asyncstorage
传递给 state 变量,但它不起作用,尝试了几个小时但仍然不起作用。 这是代码:
const [cartitems, cartitemsfunc] = useState('');
const d = async () => {
let items = await AsyncStorage.getItem('items');
console.log('items from cart:' + items);
cartitemsfunc(items);
console.log('items from cart2:' + cartitems);
};
d();
当我尝试控制台记录cartitems
时,它会在控制台中记录一个空字符串,但items
会注销该字符串
有人能告诉我哪里出错了吗
提前致谢!!!
由于setState
是异步的,您需要观察它何时完成,这可以使用useEffect
并将caritems
添加到依赖项数组中轻松完成
const [cartitems, cartitemsfunc] = useState('');
const d = async () => {
let items = await AsyncStorage.getItem('items');
console.log('items from cart:' + items);
cartitemsfunc(items);
};
useEffect(()=> {
console.log('items from cart2:' + cartitems);
}, [caritems]);
d();
正如提供的评论和链接中提到的, useState
是异步的,因此设置一个值并立即在以下行中读取它不会产生一致的结果:
cartitemsfunc(items); // async call
console.log('items from cart2:' + cartitems); // cartitems not updated yet
同样重要的是要了解,每当您使用useState
更新 state 时,组件都会再次呈现。 如果您在应用程序主体中有一个方法调用,它将在您每次更新 state 时运行。 因此,您所拥有的是一个场景,您正在调用更新 state,但该方法正在执行并最终覆盖您的更改。
const d = async () => {
let items = await AsyncStorage.getItem('items');
console.log('items from cart:' + items);
cartitemsfunc(items);
console.log('items from cart2:' + cartitems);
};
d(); // this will run every time the component renders - after you update state
如果您只需要初始渲染时的值,则从useEffect
调用该方法并将依赖链设置为[]
以便它仅在第一次渲染时运行一次,而不是每次更新 state 时运行。
下面的示例演示了从 localStorage 获取/设置值以及直接更新 state。
import React, { useState, useEffect } from "react";
import AsyncStorage from "@react-native-community/async-storage";
import "./styles.css";
export default function App() {
const [cartItems, setCartItems] = useState(null);
const setLSItems = async () => {
await AsyncStorage.setItem(
"items",
JSON.stringify([{ id: "foo", quantity: 1 }, { id: "bar", quantity: 2 }])
);
getLSItems(); // or setCartItems("Foo");
};
const clearLSItems = async () => {
await AsyncStorage.removeItem("items");
getLSItems(); // or or setCartItems(null);
};
const getLSItems = async () => {
const items = await AsyncStorage.getItem("items");
setCartItems(JSON.parse(items));
};
// bypass using local storage
const setCartItemsDirectly = () => {
setCartItems([{ id: "baz", quantity: 3 }]);
};
useEffect(() => {
getLSItems();
}, []); // run once at start
return (
<div className="App">
<div>
<button onClick={setLSItems}>Set LS Items</button>
<button onClick={clearLSItems}>Clear LS Items</button>
</div>
<div>
<button onClick={setCartItemsDirectly}>Set Cart Items Directly</button>
</div>
<hr />
{cartItems &&
cartItems.map((item, index) => (
<div key={index}>
item: {item.id} | quantity: {item.quantity}
</div>
))}
</div>
);
}
我认为在更新 state 之前执行 console.log() 语句。 因为这里已经使用了 await,所以它会在得到结果之前执行下一行。
因此,在这种情况下,我们使用 useEffect() 和 useState() 的组合。 useEffect() 用于获取数据,useState() 用于更新 state 并重新渲染 UI。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.