gpt4 book ai didi

javascript - 如何在 ReactJS 中为 API 中的每个渲染元素显示函数返回的不同值?

转载 作者:行者123 更新时间:2023-12-02 23:54:32 25 4
gpt4 key购买 nike

我正在制作一个书店购物车。我正在使用 Google 图书 API,但由于没有可用的价格,我创建了一个函数,为从 API 检索的每本书创建随机值。有没有办法让我为每本书赋予不同的值(value)?它仅呈现一个值,即每本书的最后返回值。

请注意,这只是代码的相关部分:

  constructor(props, context) {
super(props, context);
this.state = { books: [] };
}

// books are rendered on search
onTermSubmit = (term) => {
axios
.get(`https://www.googleapis.com/books/v1/volumes?q=${term}${KEY}`)
.then((res) => {
this.setState({ books: res.data.items });
})
.catch((error) => {
console.log(error);
});
};

render() {
const { books } = this.state;
const someArr = [];
let bookPrice = '';

function getRandomPrices(min, max) {
return Number((Math.random() * (max - min) + min).toFixed(2));
}

// for each book
books.forEach((book) => {
// get random price
bookPrice = getRandomPrices(2, 25);
// and assign it as a book price
someArr.push(bookPrice);
});

return (
<div>
<ul>
{books.map((book) => (
<li key={book.id}>
<div className="row">
<div className="col">
<h4>{book.volumeInfo.title}</h4>
<h6>author: {book.volumeInfo.authors}</h6>
<p>
<small>pages: {book.volumeInfo.pageCount}</small>
</p>
//HAVE NO IDEA HOW TO RENDER DIFFERENT PRICES, IT RENDERS SAME VALUE FOR EACH BOOK
price:
</div>
</div>
</li>
))}
</ul>
</div>
);
}

最佳答案

正如 @charlietfl 所说,随机价格应该在 books 数组设置为 state 的位置生成。

首先,我将你的辅助函数设为类方法:

  getRandomPrices = (min, max) => {
return Number((Math.random() * (max - min) + min).toFixed(2));
};

然后我实例化了相同的内容,生成了一个随机价格并映射了一个新的修改后的书籍数组,其中包含您的响应和随机价格:

  onTermSubmit = (term) => {
axios
.get(`https://www.googleapis.com/books/v1/volumes?q=${term}${KEY}`)
.then((res) => {
let books = res.data.items;
books = books.map((bookObj) => ({
...bookObj,
price: this.getRandomPrices(2, 25)
}));
this.setState({ books });
})
.catch((error) => {
console.log(error);
});
};

并从渲染中删除了所有冗余代码:

  render() {
// const { books } = this.state;
// const someArr = [];
// let bookPrice = '';

// // for each book
// books.forEach((book) => {
// // get random price
// bookPrice = getRandomPrices(2, 25);
// // and assign it as a book price
// someArr.push(bookPrice);
// });

return (

关于javascript - 如何在 ReactJS 中为 API 中的每个渲染元素显示函数返回的不同值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55461081/

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