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}/>
}

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

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>
)

问题在这里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')

工作样品

最新更新