首页 > 解决方案 > ““从不”类型上不存在属性“名称”

问题描述

当您在搜索框中键入匹配的名称属性时,我尝试在用户中搜索匹配的名称属性,我只是粘贴了我认为相关的重要代码。当我返回 user.name 时,useEffect 中发生错误...

任何帮助将不胜感激,我尝试记录用户,它返回一个空数组和 2 个用户对象数组,有没有办法访问单个数组,这可能是问题吗?

console.log 结果

// Create AddUser component
export const AddUser = () => {
    // Prepare states
    const [name, setName] = useState("");
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [users, setUsers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [show, setShow] = useState(false);
    const [search, setSearch] = useState("");
    const [filteredUsers, setFilteredUsers] = useState([]);

    const handleClose = () => setShow(false);
    const handleShow = () => setShow(true);
    // Fetch all users on initial render
    useEffect(() => {
        fetchUsers();
    }, []);
    // Fetch all users
    const fetchUsers = async () => {
        // Send GET request to 'users/all' endpoint
        axios
            .get("http://localhost:8000/users/all")
            .then((response) => {
                // Update the users state
                setUsers(response.data);
                // Update loading state
                setLoading(false);
            })
            .catch((error) =>
                console.error(`There was an error retrieving the user list: ${error}`)
            );
    };


    useEffect(() => {
        setFilteredUsers(
            users.filter((user) => {
                return user.name.toLowerCase().includes(search.toLowerCase());
            })
        );
    }, [search, users]);


return (
        <div>
            <Navbar bg="light" expand="lg">
                <Navbar.Brand href="#home">User Database</Navbar.Brand>
                <Navbar.Toggle aria-controls="basic-navbar-nav" />
                <Navbar.Collapse id="basic-navbar-nav">
                    <Nav className="mr-auto">
                        <Button variant="dark" onClick={handleShow}>
                            Add User
                        </Button>
                    </Nav>
                    <Form inline>
                        <FormControl
                            type="text"
                            placeholder="Search"
                            className="mr-sm-2"
                            onChange={(e) => setSearch(e.target.value)}
                        />
                        <Button variant="outline-success">Search</Button>
                    </Form>
                </Navbar.Collapse>
            </Navbar>

标签: javascriptreactjs

解决方案


推荐阅读