无法在 Reactjs 中呈现表格

时间:2020-12-20 17:47:00

标签: javascript reactjs html-table react-hooks

我正在尝试使用 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 对象。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

我正在重构你的例子。

<块引用>

不要使用 useEffect 异步。

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

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

Edit elated-hill-symxk