【问题标题】:Showing data in react table在反应表中显示数据
【发布时间】:2021-07-22 08:19:24
【问题描述】:

我已经编写了这段代码来从后端获取数据并将其显示在反应的表格中。但它显示错误。

我不知道我使用地图功能是对还是错,但这是我在其中学习和实现的。

这是我的代码。

const [comm, setcomm] = useState({
        addcomment: "",
        commdate: "",
        commid: "",
        commtime: "",
    })

    useEffect(() => {
        loadcomment(id);
    }, []);

    const loadcomment = async (id) => {
        const getcomment = await axios.get(`http://localhost:4000/getcomment/${id}`);
        setcomm(getcomment.data)
        console.log(getcomment.data);
    }

    <div className="showcomment">
                        <Table>
                            <TableHead>
                                <TableRow className="tablehead">
                                    <TableCell>Comments</TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {
                                    comm.map((com) => (
                                        <TableRow>
                                            <TableCell>
                                                {com.commdate}
                                                {com.addcomment}
                                            </TableCell>
                                        </TableRow>
                                    ))
                                }
                            </TableBody>
                        </Table>
                    </div>

这是我在此显示的错误。请帮我解决它。它表明 map 不是一个函数。我之前遇到过这个问题,但后来它起作用了,但这次它不起作用。 请帮我解决这个问题

TypeError: comm.map is not a function
UpdatePage
E:/web_development/Intern project/client/src/pages/UpdatePage/UpdatePage.jsx:266
  263 |         <TableCell>Comments</TableCell>
  264 |     </TableRow>
  265 | </TableHead>
> 266 | <TableBody>
      | ^  267 |     {
  268 |         comm.map((com) => (
  269 |             <TableRow>
View compiled

【问题讨论】:

    标签: javascript reactjs database frontend backend


    【解决方案1】:

    您不能在 comm 上映射(迭代),因为它是一个对象而不是数组。

    const [comm, setcomm] = useState({ // see, here you have an object which is not mapable
            addcomment: "",
            commdate: "",
            commid: "",
            commtime: "",
        })
    

    即使您的请求可能会用数组覆盖它,但您会在瞬间尝试映射此对象。

    【讨论】:

    • 我知道了,我已经把它改成了数组。现在它工作正常。谢谢
    • @Tanmayjoshi 随时!请把答案标记为正确的,这样其他人如果犯了类似的错误也可以找到它:)
    【解决方案2】:

    你第一次渲染它时,我假设它会使用这个 { 添加评论: ””, 指令:“”, 命令:“”, 通讯时间:“”, } 对于它的值,它实际上不是一个数组:P, 我建议在表格中使用之前先控制台记录通讯,并显示表格或表格主体,条件渲染

    【讨论】:

      猜你喜欢
      • 2019-07-04
      • 2018-05-21
      • 2017-01-09
      • 2020-10-19
      • 2022-06-24
      • 2020-07-29
      • 1970-01-01
      • 1970-01-01
      • 2018-03-22
      相关资源
      最近更新 更多