猿问

如何在反应页面上正确显示带有对象(来自另一个文件)的数组?

我在一个单独的 js 文件中有一个包含三个产品的数组:


export const products = [

                      {

                        product    : 'flash t-shirt',

                        price      :  27.50,

                        category   : 't-shirts',

                        bestSeller :  false,

                        image      : 'https://www.juniba.pk/wp-content/uploads/2018/02/the-flash-distressed-logo-t-shirt-black.png',

                        onSale     :  true

                      },

                      {

                        product    : 'batman t-shirt',

                        price      :  22.50,

                        category   : 't-shirts',

                        bestSeller :  true,

                        image      : 'https://s1.thcdn.com/productimg/1600/1600/11676326-1444552242012324.png',

                        onSale     :  false

                      },

                      {

                        product    : 'superman hat',

                        price      :  13.90,

                        category   : 'hats',

                        bestSeller :  true,

                        image      : 'https://banner2.kisspng.com/20180429/rqe/kisspng-baseball-cap-superman-logo-batman-hat-5ae5ef317f8366.9727520615250184175223.jpg',

                        onSale     :  false

                      }

   ]

然后我有一个反应文件 - 目前使用以下代码:


import React from 'react';

import {products} from './Product';


const App = function() {


    const pagedata = products.map(function(item, index){

        <p key = {index}>item.product + item.price </p>

    })


    return (

        <div className="Product">

            <header>This is a header</header>

            <div>

                <h1>All Products</h1>

                    {pagedata}

                <h1>Bestsellers</h1>

                    {pagedata}

            </div>

            <footer>This is a footer</footer>

         </div>

     );

}


export default App;

我想显示产品,但它给我一个错误:


编译失败


我错过了什么?


茅侃侃
浏览 206回答 2
2回答

芜湖不芜

const pagedata = products.map(function(item, index){&nbsp; &nbsp; <p key = {index}>item.product + item.price </p>})这部分错了。的回调函数map应该返回它产生的元素所以请尝试像这样使用const pagedata = products.map(function(item, index){&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <p key = {index}>{item.product + item.price} </p>&nbsp; &nbsp; )})

jeck猫

您需要return映射要映射的值,还需要修复您的p内容:const pagedata = products.map(function(item, index) {&nbsp; &nbsp; return <p key = {index}>{item.product + item.price}</p>;});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答