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

How to show different value returned from function for each rendered element from API in ReactJS?

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

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

  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 的位置生成。

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

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

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

  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 中的所有冗余代码:

  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 (