[英]Rendering React components with promises inside the render method
我有一個組件,它獲取一組項目作為道具並將它們map
到一組組件,這些組件被呈現為父組件的子組件。 我們使用存儲在WebSQL
圖像作為字節數組。 在map
函數中,我從項目中獲取圖像 Id 並對DAL
進行異步調用以獲取圖像的字節數組。 我的問題是我無法將承諾傳播到 React,因為它不是為了處理渲染中的承諾而設計的(無論如何我都不能說)。 我來自C#
背景,所以我想我正在尋找類似await
關鍵字的東西來重新同步分支代碼。
map
函數看起來像這樣(簡化):
var items = this.props.items.map(function (item) {
var imageSrc = Utils.getImageUrlById(item.get('ImageId')); // <-- this contains an async call
return (
<MenuItem text={item.get('ItemTitle')}
imageUrl={imageSrc} />
);
});
getImageUrlById
方法如下所示:
getImageUrlById(imageId) {
return ImageStore.getImageById(imageId).then(function (imageObject) { //<-- getImageById returns a promise
var completeUrl = getLocalImageUrl(imageObject.StandardConImage);
return completeUrl;
});
}
這不起作用,但我不知道我需要修改什么才能使其工作。 我嘗試向鏈中添加另一個承諾,但隨后出現錯誤,因為我的渲染函數返回一個承諾而不是合法的 JSX。 我在想,也許我需要利用React
生命周期方法之一來獲取數據,但由於我需要props
已經存在,我不知道在哪里可以做到這一點。
render()
方法應該從this.props
和this.state
渲染 UI,所以為了異步加載數據,你可以使用this.state
來存儲imageId: imageUrl
映射。
然后在你的componentDidMount()
方法,你可以填充imageUrl
從imageId
。 然后通過渲染this.state
對象, render()
方法應該是純粹而簡單的
注意this.state.imageUrls
是異步填充的,所以渲染出來的圖片列表項會在獲取到 url 后一一出現。 您還可以使用所有圖像 ID 或索引(不帶 url)初始化this.state.imageUrls
,這樣您就可以在加載該圖像時顯示加載器。
constructor(props) {
super(props)
this.state = {
imageUrls: []
};
}
componentDidMount() {
this.props.items.map((item) => {
ImageStore.getImageById(item.imageId).then(image => {
const mapping = {id: item.imageId, url: image.url};
const newUrls = this.state.imageUrls.slice();
newUrls.push(mapping);
this.setState({ imageUrls: newUrls });
})
});
}
render() {
return (
<div>
{this.state.imageUrls.map(mapping => (
<div>id: {mapping.id}, url: {mapping.url}</div>
))}
</div>
);
}
或者你可以使用 react-promise :
安裝軟件包:
npm i react-promise
你的代碼看起來像這樣:
import Async from 'react-promise'
var items = this.props.items.map(function (item) {
var imageSrc = Utils.getImageUrlById(item.get('ImageId')); // <-- this contains an async call
return (
<Async promise={imageSrc} then={(val) => <MenuItem text={item.get('ItemTitle')} imageUrl={val}/>} />
);
});
編輯:2019 年 10 月
react-promise 的最后一次構建提供了一個名為usePromise
的鈎子:
import usePromise from 'react-promise';
const ExampleWithAsync = (props) => {
const {value, loading} = usePromise<string>(prom)
if (loading) return null
return <div>{value}</div>}
}
完整文檔: react-promise
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.