我从父容器接收道具,我在子组件中使用Carousel来显示图像。我的代码看起来像这样:
import React, { Component } from "react";
import ReactDOM from "react-dom";
import style from './ReactSlick.less';
import Carousel from 'nuka-carousel';
export default class ReactSlick extends Component {
constructor(props) {
super(props);
this.state = {
slides:this.props.pictureArray,
};
}}
renderImages() {
return this.state.slides.map(slide => {
return (
<div key={slide._id}><img src = {slide.image} /></div>
);
}, this);
}
return (
<div className = {style.container}>
<Carousel autoplay={true}>
{this.renderImages()}
</Carousel>
</div>
);
}}
我基本上已经尝试了所有我能想到的东西,包括在componentDidMount中初始化东西。使用条件渲染来检查数组的长度,并仅在存在任何内容时显示。图片阵列是一个数组,其中包含我想要在轮播中显示的ID的图像。我从父容器中得到它,如下所示:
getImage= (key)=> {
let {getImage} = this.props;
let codeArray = [];
for (let i = 0; i < getImage._id.length; i++) {
api(getImage._id[i])
.then(res => codeArray.push(res)),
(error => console.log(error));}
return (
<Bubble
key={key}
side="left"
onImageClick={this.handleLogoClick}>
<ReactSlick pictureArray={codeArray} />
</Bubble>
);
}
当它转到子组件时,数据已经存在,并且我已经通过在构造函数中将其记录出来进行了双重检查。我尝试将API放在componentDidMount中并在子组件中设置状态,但这也不起作用。
我测试了我从本地API获取的相同数据,这似乎是从JSON工作,但是当我从远程服务器获取它时,它不起作用。它唯一一次显示来自服务器的数据是当我对代码进行更改并且活动重新加载时,数据在那里可见,但不是第一次。
我认为该组件不会重新渲染或其他东西。有没有办法对子组件进行强制刷新以使其工作?我已经阅读了一些答案,说当调用setState时它会自动触发重新渲染但在我看来似乎没有任何效果。
问题是你对asynchronous
代码进行迭代的方式。因为你试图在异步api调用的循环中填充codeArray,所以你不能使用for loop
,否则getImage
将不会等待你的api调用解析,因此当codeArray
仍为空时立即返回。所以使用其他类型的迭代器,例如可以与.map
一起使用的async code
。
这可能对你有所帮助,请查看:Using async/await with a forEach loop
/* So this doesn't work */
for (let i = 0; i < getImage._id.length; i++) {
api(getImage._id[i]).then(res => codeArray.push(res)), (error => console.log(error));
}
/* Need to find a way to wait for all `api(getImage._id[i]).then` calls
to finish first, only then should `getImage()` return.
And also take not I am placing `codeArray` in the parent's state */
async getImage () {
let codeArray = []; // just set the scope using let
await Promise.all(this.props.images.map(async (image) => {
codeArray = await api(getImage._id[i]);
}));
this.setState({ codeArray })
}
我建议在组件中调用getImage
做mount:
async componentDidMount() {
await this.getImage();
}
终于在你的render
方法:<ReactSlick pictureArray={this.state.codeArray} />
/* also set your component state
codeArrayas an empty array to be safe */
P.S:我认为images
已经从父母的道具中设定(但它也可能处于状态)。如果images
将有10个项目,并且api()
调用需要1秒才能完成,因此getImage()
将使用10 seconds
然后调用setState或更新你的组件(以及孩子ReactSlick
)
我希望这有帮助
你有props
,你为什么要使用state
迭代循环?这个的另一个解决方案是使用self-route
。因此,只要API成功获取数据。