App.js
import { Component } from 'react'
import Header from './components/Header'
import Slide from './components/Slide'
import Body from './components/Body'
import Footer from './components/Footer'
import './App.css'
import axios from 'axios'
export default class App extends Component {
constructor(props){
super(props);
this.state={
movieObj:[] //State to put the received API data
}
}
getMovies=async()=>{
//화살표함수
await axios({
method:'get',
url:'/v1/search/movie.json?query="스파이더맨"&display=6',
dataType:'json',
headers:{
"X-Naver-Client-Id":'pcSk4iqo1SpsvR7nh1Ul',
"X-Naver-Client-Secret":'g8wy7q0lQ7'
}
})
.then(response =>
{
console.log(response);
console.log(response.data.items);
this.setState({
movieObj:response.data.items
})
}
)
}
componentDidMount(){
this.getMovies()//호출
}
render() {
console.log(this.state.movieObj)
console.log(1)
return (
<div id="app">
<Header></Header>
<Slide list={this.state.movieObj}></Slide>//Passing api data to sub-component Slide
<Body></Body>
<Footer></Footer>
</div>
)
}
}Slide.js
import {Component} from 'react';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Navigation, Pagination, Autoplay, A11y } from 'swiper';
import '../css/slide.css'
// Import Swiper styles
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import 'swiper/css/scrollbar';
export default class Slide extends Component {
constructor(props){
super(props);
this.state={
slideObj:this.props.list//State to receive (this.props.list) from App.js
}
}
render() {
console.log(this.state.slideObj)
return (
<Swiper id="slide"
modules={[Navigation, Pagination, Autoplay, A11y]}
spaceBetween={50}
slidesPerView={4}
loop= {true}
//dir="ltr"//슬라이드 진행방향 전환..
navigation// prev,next
autoplay={{delay: 2000, disableOnInteraction:false}}
pagination={{ clickable: true }}
onSlideChange={() => console.log('slide change')}
onSwiper={(swiper) => console.log(swiper)}
>
<SwiperSlide className="item">
<div id='movieInfo'>
Slide1
</div>
</SwiperSlide>
<SwiperSlide className="item">Slide 2</SwiperSlide>
<SwiperSlide className="item">Slide 3</SwiperSlide>
<SwiperSlide className="item">Slide 4</SwiperSlide>
<SwiperSlide className="item">Slide 5</SwiperSlide>
<SwiperSlide className="item">Slide 6</SwiperSlide>
</Swiper>
)
}
}我试图在幻灯片中放一个api图像。在将图像放入幻灯片之前,我检查了axios接收的数据是否被正确传递。但是,由于将其发送到子组件,因此输出了一个空数组。App.js - movieObj-> Slide.js - slideObj
如何将从父组件接收的apidata数据传递给子组件?迫切需要老年人的帮助。TT
发布于 2022-09-17 16:03:13
我想您忘了在每个<img />上添加一个SwiperSlide元素。
要动态呈现从API请求检索到的图像,我们必须通过this.state.slideObj数组映射(或循环),以便用从getMovies()返回的数据填充属性(如id、src和alt )。
为了保持灵活性,我省略了一些代码:
export default class Slide extends Component {
constructor(props) {
super(props)
this.state = {
slideObj: this.props.list,
}
}
render() {
return (
<Swiper id="slide" ... >
{this.state.slideObj.map(data => (
<SwiperSlide className="item">
<img src={data.image.imageLink} alt={data.title} />
</SwiperSlide>
))}
</Swiper>
)
}
}告诉我事情进展如何?
干杯
https://stackoverflow.com/questions/73743507
复制相似问题