axios 调用后状态不更新

State does not update after axios call

我的组件如下所示:

import axios from "axios";
import React, { useState, useEffect } from "react";
import { Link } from 'react-router-dom'
import User from "./User";

const Users = () => {

    const [users, setUsers] = useState([])

    useEffect(() => {
        axios("http://localhost:8000/users")
        .then(response => setUsers(...response.data)})
        .catch(error => console.log(error))
    }, [users])

    return ( 
        <>
            <h1>All users</h1>
            <button className="btn btn-primary mb-2"><Link to="/users/create">Create</Link></button>
            <table className="table table-striped">
                <thead>
                    <tr>
                    <th scope="col">Name</th>
                    <th scope="col"></th>
                    <th scope="col">Created</th>
                    <th scope="col">Role</th>
                    <th scope="col">Action</th>
                    </tr>
                </thead>
                <tbody>
                    {users && users.map( user => <User user={user} key={user.id}/>)}

                </tbody>
            </table>
        </>
        
     );
}
 
export default Users;

当我刷新页面时,我在控制台中看到以下错误

index.js:37 Uncaught TypeError: users.map is not a function

注意:如果我在控制台中记录用户状态,我可以看到正确的数据。

我的组件有什么问题?

摆脱 ... - 您将响应数据数组分配给多个参数,而 setState 只接受一个参数。

这意味着您的用户将不是数组,而只是第一个用户。

同时摆脱 [users] 依赖以避免无限循环 - 只需将其设为 [].

左括号在哪里?

此外,如果您要设置一个状态和数组,您可能希望这样做

setState([...response.data]) 这样它将把它保存为一个数组。我不知道你 response.data 的结构如何,但如果它是一个数组,那么这将起作用。

也正如@AKX 所说,从依赖中删除 users 因为每次你 setUsersuseEffect 都会被触发到 运行 这就是你的原因有无限循环