如何在reactJS的setState中传递.JSON

时间:2019-12-31 00:08:06

标签: javascript reactjs api

当我尝试传递如下的.json时,我遇到了问题: 这是我的课程

   import MyForm from './MyForm';

   class CreateProject extends React.Component{

    constructor(){
     super();
     this.state = { categories:[]}
    }

    getCategories(){
       API.get(`/categories/public`)
          .then(resp=>{
              this.setState({categories: resp.data})
          })
          .catch(err => {
             console.log(err)
          })
    }

    ComponentDidMOunt(){
        // here show me the API correct like this
        // 0:{id:1, name:"categorie one"}
        // 1:{id:11, name:"categorie four"}
        // 2:{id:19, name:"categorie five"}
        // 3:{id:16, name:"categorie six"}
        this.getCategories()
    }
    render(){
      return(<div> <MyForm categories={this.state.categories}/></div>)
    }
}

我的功能组件

export const MyForm = ({categories}) =>{
      return(
       <div>
            <select >
                 { // here not working because .map not belong a function categories
                    categories.map(category =>(
                        <option value={category.id}>{category.name}</option>
                    ))
                 }
             </select>
       </div>)
}

如何使用循环读取功能组件内部的类别。请一些建议或小费 感谢您的关注。

1 个答案:

答案 0 :(得分:0)

我注意到的几件事 componentDidMount()拼写错误和不正确的导入。应该是:

import { MyForm } from './MyForm'

这是一个非常相似的工作示例。我只是使用一个不同的api,我有一个异步函数,还对类别添加了一些null检查(可能是多余的吗?)。

https://codesandbox.io/s/modern-frog-0wmyu

import React from "react";
import { MyForm } from "./my-form";

class CreateProject extends React.Component {
  constructor() {
    super();
    this.state = { categories: [] };
  }

  async getCategories() {
    const response = await fetch(`https://jsonplaceholder.typicode.com/posts`);
    const data = await response.json();
    this.setState({ categories: data });
  }

  componentDidMount() {
    // here show me the API correct like this
    // 0:{id:1, name:"categorie one"}
    // 1:{id:11, name:"categorie four"}
    // 2:{id:19, name:"categorie five"}
    // 3:{id:16, name:"categorie six"}
    this.getCategories();
  }

  render() {
    const { categories } = this.state;
    return (
      <div>
        {categories && categories.length > 0 && (
          <MyForm categories={categories} />
        )}
      </div>
    );
  }
}

export default CreateProject;

MyForm组件

import React from "react";

// I'm using the title property, but for your API it should be category.name
export const MyForm = ({ categories }) => (
  <select>
    {categories &&
      categories.map(category => (
        <option value={category.id}>{category.title}</option>
      ))}
  </select>
);