javascript - 如何在reactJS中的setState中传递.JSON

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

如何使用循环读取功能组件内的类别。请提出建议或提示 感谢您的关注。

最佳答案

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

从 './MyForm' 导入 { MyForm }

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

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

关于javascript - 如何在reactJS中的setState中传递.JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59538179/

相关文章:

javascript - 将带有图像路径值的 Json 文档插入到 css 背景属性中

javascript - TypeError ("Super expression must either be null or a function") - 当 App 是类而不是函数时

reactjs - 如果react js axios中没有可用数据,如何显示 "no data available"消息?

reactjs - 防止重新渲染 flatlist React Native

api - 使用 OAuth 和 PEAR Services_Twitter 获取 Twitter 请求 token 时出错

javascript - 如何将独立的JavaScript模块添加到另一个网站中

javascript - Ext.js 中 100% 高度的 TabPanel(使用 Sencha Architect)

javascript - 使用 JQuery 从生成的表中检测单击表行

javascript - FeathersJS - 如何取消错误 Hook

javascript - 使用 Redux 和 Saga 将状态保留到本地存储