[英]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.