繁体   English   中英

ReactJS Axios 它不允许我将数组分配为属性

[英]ReactJS Axios It doesn't let me assign array as property

我有一个 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} />
    }
}

附上接收 props 的组件代码:

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?

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

如果您希望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 />
       })
     </>
   )
}

暂无
暂无

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

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