当我尝试通过在react中使用使用效率从API获取数据时,我会发现问题
const [users, setUsers] = useState([]);
const getUsers = async () => {
const URL = "https://jsonplaceholder.typicode.com/users";
const response = await fetch(URL);
const data = await response.json();
console.log(data); // return 10 array .
setUsers(data);
console.log(users); // return empty Array
};
useEffect(() => {
getUsers();
}, []);
当我运行此代码并重新加载浏览器时,数据变量显示了10个数组(这是我期望的),并且用户状态不会返回空数组(这就是问题)。然后,我正在更改代码上的某些内容,然后进入浏览器,数据变量,用户表示两者都显示10个数组。 这意味着我试图告诉您,当我首次重新加载浏览器时,状态不是从数据变量设置的。
const [users, setUsers] = useState([]);
const getUsers = async () => {
const URL = "https://jsonplaceholder.typicode.com/users";
const response = await fetch(URL);
const data = await response.json();
console.log(data); // return 10 array .
setUsers(data);
console.log(users); // return empty Array
};
useEffect(() => {
getUsers();
}, []);
when I run this code and reload the browser, the data variable shows 10 arrays (that's what I expected) and the users state doesn't return an empty array (that's the problem). And then I'm changing something on code, and come to the browser, data variable and users state both shows 10 arrays.
That means I'm trying to tell you that, when I'm reloading the browser for the first time state doesn't set from data variable .
See the console result to better understand
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
设置状态是一个异步过程。这就是为什么在调用
setusers()
之后看不到即时效果的原因。相反,您可以在代码中添加另一个usefect
,并在添加此使用
使用后查看发生的更改</code 您会看到
用户
将在更新后打印。Setting a state is an asynchronous process. That's why you won't see the immediate effect after calling the
setUsers()
. Rather you can add anotheruseEffect
in your code and see the changes happening forusers
After adding this
useEffect
you will see that theusers
will be printed after it is updated.