Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/406.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在React JS中获取类别列表_Javascript_Reactjs_Fetch - Fatal编程技术网

Javascript 在React JS中获取类别列表

Javascript 在React JS中获取类别列表,javascript,reactjs,fetch,Javascript,Reactjs,Fetch,我有一个React组件,它在远程/v1/categories import React, { Component } from "react"; import axios from "axios"; import { NavigationBar } from "./NavigationBar"; class Categories extends Component { constructor(props) { super(props); this.state = {

我有一个React组件,它在远程
/v1/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;,

render()
方法中。

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

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

我想我已经找到了问题@3abirji。下一次,请您提供错误消息,以帮助人们诊断问题。它已在第121行
const{isLoaded,categories,notifications,editModeOn}=this.state上被分解此行并没有破坏categories对象,它只是将状态中的categories键对象添加到categories常量变量中。你可以试试这个。构造函数(){super();this.state={name:'stockoverflow'}}}render(){const{name}=this.state;返回({name}

)}),这也是所提供代码中发生的情况。第112行获取
类别
脱离状态(就像您的
名称
示例)。第114行和第122行
如果(!isLoaded)else…
。第145行
categories.map((category)=>
构造函数中的默认状态在第9行设置,并在第29、55和92行更新。假设API调用正确,代码确实可以工作。我将其删除并在本地运行以首先进行测试。
<ul class="categorylist">
 {
     this.state.categories.map((item,index) => {
        <li>item.name</li>
     })
 }
</ul>