[英]React component doesn't re-render after state change
我从父容器接收道具,并且在子组件中使用轮播显示图像。 我的代码如下所示:
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
仍然为空时立即返回。 因此,请使用其他类型的迭代器,例如可以与async code
一起使用的.map
。
这可能对您有帮助,请查看以下内容: 通过forEach循环使用async / await
/* 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
:
async componentDidMount() {
await this.getImage();
}
最后在您的render
方法中: <ReactSlick pictureArray={this.state.codeArray} />
/* also set your component state
codeArray /* also set your component state
as an empty array to be safe */
PS:我认为images
已经由父母的道具设置了(但是也可能处于状态)。 如果images
有10个项目,并且api()
调用需要1秒才能完成,因此getImage()
大约需要10 seconds
然后调用setState或更新您的组件(以及子ReactSlick
)
我希望这有帮助
您已有props
,为什么要使用state
来迭代循环? 为此的另一种解决方案是使用self-route
。 因此,只要API成功获取了数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.