【问题标题】:TypeError: users.map is not a function React jsTypeError:users.map 不是 React js 的函数
【发布时间】:2022-01-13 02:13:00
【问题描述】:

我遇到了一个问题,我尝试解决它很多时间但无法解决它,请尝试修复我的错误。如果您有任何疑问,请随时提出。

用户数据.js

这是我要加载后端数据库中所有数据的 userdata.js 文件

import React, { useEffect, useState } from "react";
import { Link,useParams } from "react-router-dom";
import Axios from 'axios';

const UserData = () => {
  const [users, setUser] = useState({
    title : "",
    description : ""
  });

  const {id} = useParams();

  useEffect(() => {
    AllUsers();
  }, []);

  const AllUsers = async () => {
    const res = await Axios.get(`http://localhost:3000/${id}`);
    console.log(res.data);
    setUser(res.data)
  };

  return (
    <div>
      <div className="container">
        <table className="table table-hover table-bordered mt-5">
          <thead>
            <tr>
              {/* <th scope="col">No</th> */}
              <th scope="col">Title</th>
              <th scope="col">Details</th>
              <th scope="col">Action</th>
            </tr>
          </thead>
          <tbody>
            {users.map((user, index) => (
              <tr key={index}>
                <th scope="row">{user.id}</th>
                <td>{user.title}</td>
                <td>{user.description}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default UserData;

【问题讨论】:

  • map 函数可用于数组类型的对象。这里的“用户”状态是对象类型。这就是问题所在。

标签: node.js reactjs mongodb express


【解决方案1】:

users 在我看来是一个对象,而不是一个数组。 map() 函数只存在于Array 的原型上,所以你不能在你的users 对象上调用它。你的意思是像这样初始化users吗?

 const [users, setUser] = useState([{
    title : "",
    description : ""
  }]);

【讨论】:

    【解决方案2】:

    map 方法是在数组而不是对象上定义的。让我们看看你的代码

      const [users, setUser] = useState({
        title : "",
        description : ""
      });
    

    UserData 组件中,您使用属性标题和描述定义了一个对象状态。所以users 将是一个具有这些属性的对象。因此,当您尝试在 users 对象上应用 map 时,它会失败,因为 map 不是在对象上定义的函数。

    如果你想拥有一个具有这两个属性的用户数组,你可以如下声明状态

      const [users, setUser] = useState([{
        title : "",
        description : ""
      }]);
    

    【讨论】:

      猜你喜欢
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 2020-12-23
      • 1970-01-01
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 2021-12-04
      相关资源
      最近更新 更多