我有一个React组件,在其中我执行到api rest Json的贯穿轴。
附加的组件代码
import React, { Component } from 'react';
import Axios from 'axios';
import CardsGrid from "../Pages/CardsGrid";
class Axios_cards extends Component {
constructor(props) {
super(props)
this.state = {
courses : []
}
}
// FIX ME
componentDidMount() {
Axios.get('https://my-json-server.typicode.com/jee4nc/myjsonserver/lista')
.then(response => this.setState({
courses: response.data
}))
}
render() {
const { courses } = this.state
return <div>
{console.log(courses)}
</div>
}
}
export default Axios_cards;
为了验证是否收到阵列,我放置了console.log。我可以看到,如果ARRAY收到了我:
当我想通过props将数组分配给另一个组件时出现问题:
render() {
const { courses } = this.state
return <CardsGrid courses= {courses} />
}
}
接收道具的附加组件代码:
import React from 'react';
import Cards from "../Molecules/Cards"
const CardsGrid = ({courses}) => (
//FIX ME
<div>
{console.log(courses)}
</div>
)
export default CardsGrid;
CardsGrid内的console.log将其返回给我:“未定义”
为什么CardsGrid组件无法识别通过props分配的数组?
我认为问题在于您执行销毁的方式。
如果要在CardsGrid
中使用每个项目,我建议将.map
与spread operator一起使用。原因是您有一个对象数组,并且您可能希望每个数组的单独键成为每张卡的道具(尽管您的代码并未显示应如何渲染):
render() {
// destructure all the courses from the state obj
const { courses } = this.state
return (
// use fragments to offset your JSX return and eliminate useless <div>
<>
// Loop over your courses array with .map
courses.map( (course) => {
// ...course will spread each key into CardsGrid as a prop
// each key's value will automatically be assigned to the prop
<CardsGrid ...course />
})
</>
)
}