【问题标题】:React 17.0.1 map is undefinedReact 17.0.1 地图未定义
【发布时间】:2021-06-01 16:34:33
【问题描述】:

您好,我正在尝试从 Axios 获取请求中收到的 json 数据创建一个动态表。

const [projectData, setprojectData] = useState({});
const [schedule, setSchedule] = useState({});

useEffect(() => {
    Axios.get(`/fetch-project-details/${id}`, {}).then((response) => {
        setprojectData(result[0]);
        setSchedule(JSON.parse(result[0].p_schedule));
});


return (
    <div>
    schedule.map((value) => { // How to return the key value pairs as a table format
        return (
          <tr>{value.id}</tr>
          <th>{value.keys}</th>
        )
    })
)

这是我在计划状态

中得到的
[
{
    "Sno": "1",
    "First Name": "name",
    "Last Name": "las2t name",
    "Email": "test@gmail.com",
    "Amount": "2000"
},
{
    "Sno": "1",
    "First Name": "first name",
    "Last Name": "last name",
    "Email": "test2@gmail.com",
    "Amount": "2000"
}
]

如何将 key 作为 thead 和 pair 作为 tbody 返回??

【问题讨论】:

  • 你的初始状态不是数组。
  • 您可能还想在useEffect 上添加一个依赖列表,这样它就不会在每次渲染时都运行。 (顺便说一句,导致无限渲染)

标签: reactjs


【解决方案1】:
// const [schedule, setSchedule] = useState({});
const [schedule, setSchedule] = useState([]);

return (
    <div>
    {
      schedule.map((value) => { 
        return (
          <tr>{value.id}</tr>
          <th>{value.keys}</th>
        )
      })
    }
    </div>
)

【讨论】:

  • 谢谢,我收到此错误 - 对象作为 React 子项无效(发现:带键的对象 {......} 如果您打算渲染一组子项,请使用一个数组。
  • 将地图调用封装在{}
  • 您需要将渲染中的schedule.map() 部分包围在{} 内。这将评估{} 中的表达式。之后还要关闭&lt;div&gt;
  • 我已经添加了,你能帮我根据数组对象动态创建表吗
【解决方案2】:
    return is executed before the schedule is set by setSchedule. so you can add a null check in return.
     <div>
       {schedule && ( schedule.map((value) => {
            return (
              <tr>{value.id}</tr>
              <th>{value.keys}</th>
            )
        }) )}

or use ? operator like schedule?.map((value)

【讨论】:

  • 如何获取键值对以将其显示在带有thead和tbody的表格中
猜你喜欢
  • 1970-01-01
  • 2019-03-14
  • 2014-08-26
  • 2020-02-10
  • 2021-04-16
  • 2017-03-26
  • 2021-09-09
  • 2017-02-21
  • 2018-01-05
相关资源
最近更新 更多