首页 > 解决方案 > axios 不返回数组 ReactJS

问题描述

我正在使用 axios 来获取带有数组的 json 服务器

附加的json数组

http://my-json-server.typicode.com/jee4nc/myjsonserver/lista

问题是我想通过它的属性将该对象列表分配给另一个组件

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 : []
        }      
    }

    componentDidMount() {
        axios.get('http://my-json-server.typicode.com/jee4nc/myjsonserver/lista')
        .then(response => this.setState({
                courses: response.data
            }))
    }
    render() {
        const {courses} = this.state
        return <CardsGrid courses={courses}/
    }
}

export default Axios_cards;

正是在这里

render() {
        const {courses} = this.state
        return <CardsGrid courses={courses}/>
    }

接收对象列表作为道具的组件没有接收数组,因为我进行了验证以验证它 我附加了我通过道具分配数组的组件

const CardsGrid = ({courses}) => (
    <div className="ed-grid m-grid-3">
            {
                Array.isArray(courses) ?
            courses.map( e => 
                <Cards 
                id={e.id} 
                title={e.title} 
                description={e.description}
                image={e.image}
                price={e.price}
                key={e.id}  
                />) : null
            }
        </div>
)

标签: javascriptreactjsaxios

解决方案


问题就在这里axios.get('http://my-json-server.typicode.com/jee4nc/myjsonserver/lista')。很可能您正在通过安全 (https) 连接(即https://my-app)打开您的应用程序。但在代码中,您试图获取不安全的 (http) 资源。这称为混合内容并被浏览器阻止。您可以在此处阅读有关此内容的更多信息

所以要解决,只需使用 https 端点。您的后端似乎支持 https 请求。

axios.get('https://my-json-server.typicode.com/jee4nc/myjsonserver/lista')

工作样本


推荐阅读