[英]how to passing a .JSON in setState in reactJS
我有一個問題,當我嘗試像這樣傳遞 .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()
拼寫錯誤和不正確的導入的幾件事。 應該:
import { MyForm } from './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>
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.