gpt4 book ai didi

javascript - React 从 map 函数渲染一系列图像时遇到问题

转载 作者:行者123 更新时间:2023-11-29 16:40:54 25 4
gpt4 key购买 nike

我正在尝试设计一个组件,用户可以单击一个按钮,该按钮将触发 giphy API 调用,最终渲染一系列 gif 图像。

到目前为止,除了实际的图像渲染之外,我能够成功完成所有工作。到目前为止,这是我的代码:

retrieveURLs() {
*bunch of stuff to make API call and return an array of URLs related
to the category of the button the user pushes*
}
renderGifs() {
this.retrieveURLs().then(function(results) {
console.log(results); //logs array of URLs
return results.map(function(url, index) {
console.log(url); //logs each url
return (<img key={index} src={url} alt="" />)
}, this);
});
}
render() {
return(
<div id="gif-div">
{this.renderGifs()}
</div>
)
}

尽管每个 console.log() 事件都表明 URL 至少已正确传递,但什么也没有呈现。

我对父组件执行类似的操作,以呈现如下所示的类别数组中的按钮:

btnArray = [*bunch of categories here*];
renderButtons() {
return btnArray.map(function(item, i) {
let btnID = btnArray[i].replace(/\s+/g, "+");
return <button type='button' className="btn btn-info" onClick={this.handleCategorySelect} key={i} id={btnID} value={btnID}>{btnArray[i]}</button>
}, this)
}

按钮已正确渲染,但我的图像未正确渲染。 renderbuttons 和 rendergifs 方法都不会改变状态。老实说,我看不出两者之间有什么有意义的区别,所以我想得到一些帮助来弄清楚为什么一个有效而另一个无效。

最佳答案

这就是异步函数的本质;您无法从回调中返回原始调用站点的值。如果你要写:

const res = this.retrieveURLs().then(function(results) {
return results;
});

您只会更改 promise 的分辨率值。 res 不会被赋予 results 的值,而是被赋予由 this.retrieveURLs() 创建的 promise ,检索已解析 Promise 的值的唯一方法是附加 .then 回调。


你可以做的是:

this.retrieveURLs().then(results => {
this.setState({ images: results });
});

现在,您的内部状态将异步更新,并且您的组件将被告知使用新数据重新渲染,您可以通过访问状态在渲染函数中使用这些数据。

注意:在上面的示例中,我使用箭头函数来创建回调,因为否则 this 将不会绑定(bind)到正确的上下文。或者,您可以使用旧的 that = this 技巧,或使用 Function#bind

关于javascript - React 从 map 函数渲染一系列图像时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46040876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com