You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目中无法渲染<h1>标签问题求助

解决React中标题无法渲染的问题

嘿,我看到你遇到的问题了——标题USER LIST INFO没法正常显示,咱们一步步来搞定它:

问题根源

  1. 不可达代码:在你的render方法里,return语句之后的ReactDOM.render(element, ...)永远不会执行。因为return会直接退出函数,后面的代码根本跑不到。在React类组件中,我们只需要在render方法里返回要渲染的JSX即可,不需要再调用ReactDOM.render。
  2. 无效的HTML结构:你的表格里嵌套了很多不符合规范的div——比如<tr>里不能直接放<div>,<tbody>里也不能用<div>包裹<tr>,这些错误可能会影响整个组件的渲染逻辑。

修复方案

下面是修改后的完整代码,我标注了关键修改点:

import React, { Component } from 'react'
import './App.css';
import ReactPaginate from 'react-paginate'
import axios from 'axios'

class App extends Component {
 constructor(props){
 super(props)
 this.state = {
 users:[],
 isLoading:false,
 isError:false,
 };
 }

 // 优化数据获取:用Promise.all同时请求两个页面,避免嵌套
 async componentDidMount (){
 this.setState({isLoading:true})
 try {
   // 同时发起两个请求,等待全部完成
   const [response1, response2] = await Promise.all([
     fetch("https://reqres.in/api/users?page=1"),
     fetch("https://reqres.in/api/users?page=2")
   ])

   if(!response1.ok || !response2.ok) throw new Error('请求失败')

   const data1 = await response1.json()
   const data2 = await response2.json()
   // 合并两个页面的用户数据
   const allUsers = [...data1.data, ...data2.data]
   this.setState({users: allUsers, isLoading:false})
 } catch (err) {
   this.setState({isError:true, isLoading:false})
 }
 }

 renderTableRows = () => {
 return this.state.users.map(user => {
   return (
     // 修复:tr里只能放td,把avatar放到td中
     <tr key={user.id}>
       <td className="avatar">
         <img src={user.avatar} alt={`${user.first_name} ${user.last_name}`}/>
       </td>
       <td>{user.first_name}</td>
       <td>{user.last_name}</td>
       <td>{user.email}</td>
     </tr>
   )
 })
 }

 render(){
 const {users, isLoading, isError} = this.state

 if(isLoading){
   return <div>Loading...</div>
 }
 if(isError){
   return <div>Error...</div>
 }

 // 修复:把标题直接放到返回的JSX里,同时修正表格结构
 return (
   <div className="user-container">
     <h1>USER LIST INFO</h1>
     <table>
       <thead>
         <tr>
           <th>Avatar</th>
           <th>First Name</th>
           <th>Last Name</th>
           <th>Email</th>
         </tr>
       </thead>
       <tbody>
         {/* 修复:tbody直接放tr,不需要div包裹 */}
         {this.renderTableRows()}
       </tbody>
     </table>
   </div>
 )
 }
}

export default App

关键修改说明

  • 标题渲染:把h1标题直接放在返回的JSX结构中,放在表格外面,确保它能被正常渲染。
  • 修复HTML结构:移除了表格中不符合规范的div嵌套,比如把头像放在td里,tbody直接渲染tr元素,保证DOM结构的合法性。
  • 优化数据请求:用Promise.all同时请求两个页面的数据,代码更简洁,性能也更好,避免了嵌套的if判断。

这样修改之后,你的标题应该能正常显示,表格结构也更规范啦!

内容的提问来源于stack exchange,提问作者Anugrah Bhatt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 13:12:36