【发布时间】:2020-08-13 08:54:34
【问题描述】:
我正在尝试在打开我的模式后进行异步获取调用。我需要那个调用,因为它获取了图像,并且获取响应大约需要 5 秒。
所以模式应该首先显示数据,然后一旦获取完成,它也应该显示获取数据。
我的问题是,在使用 () => {this.fetchImages(id) 调用函数时,它没有被调用。我认为这是因为该函数被分配而不是被调用。
但是当我在没有() => 的情况下调用函数fetchImages() 时,我得到了这个错误:
Invariant Violation: Minified React error #31
这是我的代码,为简单起见已删除无关部分:
renderModal = () => {
...
return (
<Modal open={openModal != null} onClose={this.closeModal}
little showCloseIcon={true} styles={modalStyles}>
<div className="item">
...
{() => {this.fetchImages(id)
.then(r => console.log("Fetch result" + r))}}
</div>
</Modal>
);
}
fetchImages = async (id) =>{
console.log("Request started")
try{
let myImages = null;
if(typeof(id) !== 'undefined' && id != null) {
myImages = await fetchImages(id);
console.log("Images: " + myImages);
return (
<div>
{Array.isArray(myImages) && myImages.length !== 0 && myImages.map((item, key) =>
<p>Image name: {item.name}, En device name: {item.name.en_US}</p>
)}
</div>
);
}
} catch (e) {
console.log("Failed")
}
}
编辑
通过按照jack.benson 和GalAbra 的建议更改代码,我遇到了陷入死循环的问题。我将添加新代码:
一旦页面加载完毕,renderModal 就会在 render() 方法中调用:
{this.renderModal()}
然后我有一个显示模态的按钮,因为模态包含一行:
<Modal open={openModal != null} onClose={this.closeModal}
little showCloseIcon={true} styles={modalStyles}>
从这里调用:
myMethod = (task) => {
...
return (
<div {...attrs}>
...
<button onClick={() => {this.showModal(documents[0])}}>{translate('show_more')} »</button>
</div>
}
</div>
</div>
);};
以及显示模态的部分:
showModal = (document) => {
this.setState({ modalOpen: document });
};
现在是新的renderModal():
renderModal = () => {
const doThing = async () => {
try {
const newImages = await downloadDeviceImages(id);
return { data: newImages };
} catch (e) {
console.log("Failed")
}
};
const test = async (id) => {
const imageData = await doThing(id);
console.log("after", imageData.data);
this.setState({
imageData: imageData.data
});
};
if(typeof(id) !== 'undefined' && id != null) {test(id);}
return (
<Modal open={openModal != null} onClose={this.closeModal}
little showCloseIcon={true} styles={modalStyles}>
<div className="item">
...
<div>
{this.state.imageData.map((item, key) =>
<p>Device name: {item.name}, En device name: {item.name.en_US}</p>
)}
</div>
</Modal>
);
}
这里的主要部分是该按钮将被多次单击,并且每次单击时可能具有不同的 ID,因此每次都应发出新请求。
【问题讨论】:
标签: reactjs react-native asynchronous async-await fetch