当我尝试通过在react中使用使用效率从API获取数据时,我会发现问题

发布于 2025-01-31 05:18:57 字数 567 浏览 3 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陌伤ぢ 2025-02-07 05:18:57

设置状态是一个异步过程。这就是为什么在调用setusers()之后看不到即时效果的原因。相反,您可以在代码中添加另一个usefect,并在添加此使用使用后查看发生的更改<

// ... other code
useEffect(() => {
    // this will run after the 'users' has been changed
    console.log("Users", users)
}, [users]);
// ...

/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 another useEffect in your code and see the changes happening for users

// ... other code
useEffect(() => {
    // this will run after the 'users' has been changed
    console.log("Users", users)
}, [users]);
// ...

After adding this useEffect you will see that the users will be printed after it is updated.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文