0

我有一个 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 分配的 Array?

4

1 回答 1

1

我认为问题在于您如何执行解构。

如果您希望每个项目都支持CardsGrid,我建议您使用.map扩展运算符。原因是您有一个对象数组,并且您可能希望每个数组的单独键成为每张卡的道具(尽管您的代码没有显示太多应该如何呈现):

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 />
       })
     </>
   )
}
于 2020-02-10T02:55:11.997 回答