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

React组件改造:实现分类列表获取并渲染为<ul>列表

我来帮你梳理怎么实现这个需求,其实你已经有了基础的组件结构,咱们可以优化下获取分类列表的逻辑,同时确保渲染出符合要求的<ul><li>...</li></ul>结构:

1. 优化分类列表获取逻辑

你现有的componentDidMount里已经在拉取分类,但可以简化冗余代码,不用单独维护catN数组(后续需要分类名称直接从categories里提取就行),让状态更简洁:

componentDidMount() {
  axios
    .get("/v1/categories")
    .then((res) => {
      this.setState({
        isLoaded: true,
        categories: res.data.items, // 直接存储接口返回的分类数组
        notification: "",
      });
    })
    .catch((error) => {
      console.error("加载分类列表失败:", error);
      this.setState({ notification: "加载分类失败,请稍后重试" });
    });
}
2. 渲染标准的ul-li列表结构

调整render里的列表渲染部分,确保严格遵循<ul>包裹<li>的结构,同时修复编辑模式下的DOM层级问题:

<ul className="categories">
  {categories.map((category) => (
    <li key={category.id} className="lispace" onDoubleClick={this.editMode}>
      {editModeOn ? (
        <div>
          <input 
            className="input" 
            type="text" 
            defaultValue={category.name} 
          />
          <button onClick={this.exitEditMode} className="button">保存编辑</button>
        </div>
      ) : (
        <>
          {category.name}
          <button 
            onClick={(e) => this.deleteCategory(category)} 
            type="button" 
            className="dbutton"
          >
            删除分类
          </button>
        </>
      )}
    </li>
  ))}
</ul>

这里做了几个关键调整:

  • 用category.id作为列表项的key(比name更可靠,避免重名分类的key冲突)
  • 编辑模式的内容放在<li>内部,保持ul-li的正确HTML层级,不会破坏结构
  • 用React片段<>包裹非编辑模式的内容,避免生成多余的DOM节点
  • 把编辑按钮文字改成“保存编辑”,语义更清晰
3. 额外的逻辑优化(可选)

为了让组件更健壮,还可以做这些调整:

  • 去掉冗余的catN状态,判断分类是否存在直接用数组的some方法:
// 在addCategory方法里
const categoryExists = this.state.categories.some(cat => cat.name === newCategory);
  • 修复添加分类时的状态更新错误,等接口请求成功后再更新本地状态(避免本地和服务器数据不一致):
// 修改addCategory里的接口请求部分
axios
  .post(
    "/v1/categories",
    { name: newCategory },
    { headers: { Authorization: "12345" }, }
  )
  .then((res) => {
    console.log(res);
    this.setState(prevState => ({
      categories: [...prevState.categories, res.data], // 用接口返回的新分类数据更新状态
      notifications: "",
    }));
  })
  .catch((error) => {
    console.error("添加分类失败:", error);
    this.setState({ notifications: "添加分类失败,请稍后重试" });
  });
  • 删除分类时同样等接口成功后再更新本地状态:
deleteCategory(category) {
  axios
    .delete(`/v1/categories/${category.id}`, { headers: { Authorization: "12345" }, })
    .then((res) => {
      console.log(res);
      this.setState(prevState => ({
        categories: prevState.categories.filter(cat => cat.id !== category.id)
      }));
    })
    .catch((error) => {
      console.error("删除分类失败:", error);
      this.setState({ notifications: "删除分类失败,请稍后重试" });
    });
}

调整后,你的组件就能正确获取分类列表,并渲染出标准的ul-li结构,同时逻辑更稳定,减少了数据不一致的风险。

内容的提问来源于stack exchange,提问作者3abirji

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 08:12:40