简体   繁体   English

如何在reactJS的setState中传递.JSON

[英]how to passing a .JSON in setState in reactJS

I have a problem, when I try to pass a .json like this: this is my class我有一个问题,当我尝试像这样传递 .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>)
    }
}

my functional component我的功能组件

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>)
}

how to read a categories inside my functional component using a loop .如何使用循环读取我的功能组件中的类别。 please something suggestion or a tip thanks for your attention.请一些建议或提示感谢您的关注。

A couple things I noticed componentDidMount() spelling error and an incorrect import.我注意到componentDidMount()拼写错误和不正确的导入的几件事。 Should be:应该:

import { MyForm } from './MyForm'

Here's a very similar working example.这是一个非常相似的工作示例。 I'm just using a different api and I have an async function, also added some null checks on categories (might be redundant?).我只是使用不同的 api 并且我有一个异步函数,还添加了一些对类别的空检查(可能是多余的?)。

https://codesandbox.io/s/modern-frog-0wmyu 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 component 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>
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM