【问题标题】:Unable to render Table in Reactjs无法在 Reactjs 中呈现表格
【发布时间】:2020-12-21 02:17:38
【问题描述】:

我正在尝试使用 api(sample response) 来提供对象列表并将其呈现在表中以做出反应。以下是我的代码。我收到错误data is not defined

Here is the code when I hardcoded data, the table got rendered perfectly

import React, { useEffect, useState } from "react";

function renderTableData() {
    return data.map((student, index) => {
        const { config, text, source_link, tab_type } = student //destructuring
        return (
            <tr key={config}>
                <td>{config}</td>
                <td>{text}</td>
                <td>{source_link}</td>
                <td>{tab_type}</td>
            </tr>
        )
    })
}

const useFetch = (url) => {
    const [data, setData] = useState('');
    const [loading, setLoading] = useState(true);
    useEffect(async () => {
        const response = await fetch(url, {
            method: 'GET',
        })
        const data = await response.json()
        console.log(data)
        setData(data)
        setLoading(false)
    }, []);
    return { data, loading };
}

export default function CreateTestcaseStep2() {
    const { data, loading } = useFetch(ENPOINT_URL_GOES_HERE)

    return (
        <div>
            <h1 id='title'>React Dynamic Table</h1>
            <table id='students'>
                <tbody>
                    {renderTableData()}
                </tbody>
            </table>
        </div>
    );
}

请指出我做错了什么,因为renderTableData 函数无法获取data 对象。

【问题讨论】:

  • 也许 fetch(..).then(response => response.json()).then(json => {...})
  • 还尝试将默认数据初始化为空数组,例如 const [data, setData] = useState({data:[]});这样你就可以返回( {data.lenght > 0 && ....
  • 将数据传递给您的 renderTableData() 函数。
  • @ToddSkelton 我也试过了{renderTableData({data})},但抛出错误data.map is not a function

标签: javascript reactjs html-table react-hooks


【解决方案1】:

renderTableData 定义在您的功能组件外部 并且您在其中引用data 变量,我想它不知道要引用哪个data 变量?我很惊讶你没有收到关于此的错误。

尝试将data 变量作为参数传递给函数。

【讨论】:

  • @Mahesh 请先 console.log 数据看看你传递了什么
  • @Mahesh 这是你设置它之前。在 useState 中使用 [] 的初始值而不是 ''。
  • 刚刚替换 [] 代替 '' 并且数据得到了完美呈现。非常感谢@giorgim
  • @Mahesh map 是一个应该在数组上调用的函数,而不是字符串
  • @Mahesh 最好不要忽略它,这里有一些关于它的阅读:reactjs.org/docs/lists-and-keys.html
【解决方案2】:

我正在重构你的例子。

不要使用useEffect asyc。

useEffect(() => {
    axios.get(url).then((response) => {
      setData(response);
      setLoading(false);
    });
}, [url]);

如果你想用函数制作表体,需要使用参数传递数据。

const renderTableData = (data) => {
                      // ^^^^  Pass data using function parameters, 
                      // this function it's possible to use in another table with the same data
  return data?.map((student) => {
    const { id, name, username, email } = student;
    return (
      <tr key={id}>
        <td>{name}</td>
        <td>{username}</td>
        <td>{email}</td>
      </tr>
    );
  });
};

用函数传递状态渲染表体

<tbody>{renderTableData(data)}</tbody>
                     // ^^^^ Passing state to render table body

查看现场演示,使用参数将数据传递给函数:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-02
    • 2012-08-23
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 2018-04-08
    • 2018-01-03
    相关资源
    最近更新 更多