gpt4 book ai didi

javascript - 将背景图像保存到状态

转载 作者:行者123 更新时间:2023-11-30 20:14:35 24 4
gpt4 key购买 nike

我正在尝试使用 React 构建一个纸牌内存游戏,其中纸牌是来自 http://robohash.org 的机器人.我的卡片阵列看起来像这样:

{id: 0, cardState: CardState.1, backgroundImage: ''},
{id: 1, cardState: CardState.1, backgroundImage: ''},

由于使用 onClick 在每张卡片上调用 url("https://robohash.org/ ...") 需要很长时间,所以我尝试使用 axios.get 获取机器人,然后将它们保存到状态。但是,无论我尝试什么,我似乎都无法让它发挥作用。

我的函数看起来是这样的(我有 16 张卡片,所以我需要 8 个机器人乘以两次)

async fetchRobots() {
let cards = [...this.state.cards];
let robots = [...this.state.robots];
for (let i = 0; i < 8; i++) {
try {
const resp = await axios.get(`https://robohash.org/${i}?size:150x150`);
robots.push(resp.data, resp.data);
} catch (e) {

}
}
this.setState({
cards: cards.map((card, i) => {
card.backgroundImage = "url(data:image/png," + robots[i];
})
});
}

我试过将“base64”添加到标题中,但它也不起作用。有什么方法可以将图像保存到状态并让它显示?

预先感谢您的帮助!

最佳答案

状态是不可变的。您不能只按状态推送对象或按预期更新它们。

要更改状态,您需要调用 this.setState({robots: yourArray}); 例如,这将使用新数组更新状态。每当状态被修改时,这将在 React 中触发重新渲染。

关于javascript - 将背景图像保存到状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52055085/

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