【问题标题】:Fetch a list of categories in React JS获取 React JS 中的类别列表
【发布时间】:2020-06-19 12:57:09
【问题描述】:

我有这个 React 组件可以在远程 /v1/categories 中创建和删除 categories

import React, { Component } from "react";
import axios from "axios";
import { NavigationBar } from "./NavigationBar";

class Categories extends Component {
  constructor(props) {
    super(props);
    this.state = {
      categories: [],
      catN: [],
      isLoaded: false,
      editModeOn: false, 
    };
  }

  componentDidMount() {
    axios
      .get("/v1/categories")
      .then((res) => {
        var cats = [],
          catsN = [];
        for (var i = 0; i < res.data.items.length; i++) {
          cats[i] = res.data.items[i];
          catsN[i] = cats[i].name;
        }
        console.log(res);
        this.setState({
          isLoaded: true,
          categories: cats,
          catN: catsN,
          notification: "",
        });
      })
      .catch((error) => console.log("Get Error"));
  }
  // Add category
  addCategory(e) {
    e.preventDefault();
    const { catN } = this.state;
    const newCategory = this.newCategory.value;
    const categoryExists = catN.includes(newCategory);

    this.setState({
      editModeOn: false,
    });

    if (categoryExists) {
      this.setState({
        notifications: "Category is already there!",
      });
    } else {
      newCategory !== "" &&
        this.setState({
          // no redundancy
          categories: [...this.state.categories, this.newCategory],
          notifications: "",
        });

      this.addForm.reset();
      axios
        .post(
          "/v1/categories",
          { name: newCategory },
          {
            headers: { Authorization: "12345" },
          }
        ) // Post request for new category
        .then((res) => {
          console.log(res);
        })
        .catch((error) => console.log(error));
    }
  }
  // Delete a category
  deleteCategory(category) {
    console.log(category);
    const newCategories = this.state.categories.filter((categories) => {

      return categories !== category;
    });
    this.addForm.reset();
    axios
      .delete("/v1/categories/" + category.id, {
        headers: { Authorization: "12345" },
      })
      .then((res) => {
        console.log(res);
      })
      .catch((error) => console.log(error));

    this.setState({
      categories: [...newCategories],
    });
  }

  editMode = () => {
    this.setState({
      editModeOn: true,
    });
    console.log("doubleclick"); 
  };

  exitEditMode = () => {

    this.setState({
      editModeOn: false,
    });
    console.log("works");
  };

  render() {
    const { isLoaded, categories, notifications, editModeOn } = this.state;

    if (!isLoaded) {

      return (
        <div>
          <NavigationBar />
          <div className="loading">Loading...</div>
        </div>
      );
    } else {
      return (
        <div>
          <NavigationBar />
          <form
            ref={(input) => (this.addForm = input)}
            onSubmit={(e) => {
              this.addCategory(e);
            }}
          >
            {notifications !== "" && <p className="noti">{notifications}</p>}
            <input
              ref={(input) => (this.newCategory = input)}
              type="text"
              placeholder="Category"
              className="input"
            />
            <button type="submit" className="button">
              Add Category
            </button>
          </form>

          <ul className="categories">
            {categories.map((category) =>
              editModeOn ? (
                <div>
                  <input
                    key={category.name}
                    className="input"
                    type="text"
                    defaultValue={category.name}
                  />
                  <button onClick={this.exitEditMode} className="button">
                    Edit
                  </button>
                </div>
              ) : (
                <li
                  key={category.name}
                  className="lispace"
                  onDoubleClick={this.editMode}
                >
                  {category.name}
                  <button
                    onClick={(e) => this.deleteCategory(category)}
                    type="button"
                    className="dbutton"
                  >
                    Delete Category
                  </button>
                </li>
              )
            )}
          </ul>
        </div>
      );
    }
  }
}
export default Categories;,

我想编写一个方法来获取categories 的列表并能够将其作为列表返回

<ul> 
<li> category 1 </li>
<li> category 2 </li>
</ul>

render() 方法中。

【问题讨论】:

  • 我想我找到了问题@3abirji。下次能否请您也提供错误消息以帮助人们诊断问题。

标签: javascript reactjs fetch


【解决方案1】:

使用您在 componentdidmount 生命周期中设置的类别状态,该调用希望应该包含 list 中的所有类别。考虑到这一点,请在渲染函数中使用以下代码。

<ul class="categorylist">
 {
     this.state.categories.map((item,index) => {
        <li>item.name</li>
     })
 }
</ul>

【讨论】:

  • 它已在第 121 行被解构 const { isLoaded, categories, notifications, editModeOn } = this.state;
  • 这一行并没有破坏类别对象,它只是将状态中的类别关键对象添加到类别常量变量中。你可以试试这个。构造函数(){ 超级(); this.state ={name : 'stockoverflow'} } 渲染(){ const {name} = this.state;返回 (

    {name}

    ) }
  • 在提供的代码中也是如此。第 112 行让 categories 脱离状态(就像你的 name 示例)。第 114 和 122 行if(!isLoaded) else ...。第 145 行categories.map((category) =&gt;constructor 中的默认状态在第 9 行设置并在第 29、55 和 92 行更新。假设 API 调用是正确的,代码确实有效。我先将其存根并在本地运行以进行测试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-04
  • 1970-01-01
  • 1970-01-01
  • 2018-07-20
  • 1970-01-01
  • 2019-02-23
相关资源
最近更新 更多