我正在使用 React owl carousel显示动态轮播。
当我放置静态html时,它会在轮播中正确显示数据
,但是当我尝试显示动态数据
(使用axios)时轮播总是空白
.
注意::我使用 axios 获取数据并更新用于循环数据的状态。
有人可以解释一下我在这里犯了什么错误,因为轮播始终保持空白。
所有代码都在同一个文件中:
我的代码::
import React, { Component } from 'react';
import HeaderComponent from '../Common/Header';
import SidebarComponent from '../Common/Sidebar';
import TrendingStoriesComponent from './TrendingStories';
import FlashDealsComponent from './FlashDeals';
import WeeklyPicksComponent from './WeeklyPicks';
import OwlCarousel from 'react-owl-carousel';
import 'owl.carousel/dist/assets/owl.carousel.css';
import 'owl.carousel/dist/assets/owl.theme.default.css';
import axios from 'axios';
import moment from 'moment';
class HomeComponent extends Component {
constructor(props) {
super(props);
this.state = {
latest_stories: [],
}
}
componentDidMount() {
axios.get(process.env.REACT_APP_API_ENDPOINT+'/story/latest_stories')
.then((response) => {
// handle success
console.log(response);
this.setState({
latest_stories: response.data.response,
});
})
.catch(error => {
//Error object contains the response property
console.log(error);
});
}
render() {
return (
<>
<HeaderComponent />
<SidebarComponent />
<section className="weeklypick mt-4">
<div className="weeklyslider">
<OwlCarousel
className="owl-theme"
loop
margin={10}
nav
>
{
this.state.latest_stories.map((story,index) => {
console.log(story);//this prints successfully everytime in loop
return <div className="item" key={'latest-story-'+index}>
<div className="sliderbox">
<h6>
<span>25 Jan</span>
<img src="assets/images/dropdown.svg" alt="" />
</h6>
<div className="sliderboxfield">
<span className="yellowbadge">Adventures</span>
<img src="assets/images/car1.svg" alt="" />
</div>
<div className="textboxfield">
<p>I Visited Lush’s Biggest Ever Shop & The Treatments Will Truly Blow Your
Mind</p>
<ul>
<li>
<a href="#">BY SARAH STEVENS</a>
</li>
<li>
<a href="#">
<img src="assets/images/heart.svg" alt="" />
<span className="likecount">3.2k</span>
</a>
</li>
</ul>
</div>
</div>
</div>
})
}
</OwlCarousel>
</div>
</section>
</>
);
}
}
export default HomeComponent;
最佳答案
似乎 OwlCarousel 不会在状态更改时重新渲染,因此即使您的状态更新并且您的回调向其发送新的子集,OwlCarousel 仍保持与初始渲染一样。它确实有回调 Hook ,您可以将更新绑定(bind)到其中,以便它可以使用它进行更新,但看起来文档非常差,所以我没有花时间在它上面。有一个名为 onRefresh
钩子(Hook),您可以使用它来接收函数,但同样没有示例告诉您如何执行此操作。 https://owlcarousel2.github.io/OwlCarousel2/docs/api-events.html
为了克服这个问题,我将 OwlCarousel 包装在长度检查中,只有在 API 调用返回后状态有需要渲染的内容时才会渲染。
{this.state.latest_stories.length && (
<OwlCarousel className="owl-theme" loop margin={10} nav>
{this.state.latest_stories.map((story, index) => {
console.log(story); //this prints successfully everytime in loop
return (
<>
<div className="item">
<h4>{story}</h4>
</div>
</>
);
})}
</OwlCarousel>
)}
这是基于您的代码的工作示例:https://codesandbox.io/s/recursing-hooks-gz5gl
关于javascript - React owl 轮播是空白的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56771532/