首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >响应js组件--平均函数的问题--我使用的是db.json假api调用

响应js组件--平均函数的问题--我使用的是db.json假api调用
EN

Stack Overflow用户
提问于 2020-12-03 01:15:21
回答 2查看 74关注 0票数 0

我在本地主机上使用假db.json :3000,并在另一台服务器上运行react.js。新的react.js代码。

我需要得到在我的db.json文件中的评论明星评分的平均值。

这是破坏站点的代码函数.

代码语言:javascript
复制
    const getAverage = (reviews) => {
        reviews.map((review) => {
            return review.stars.reduce((a.review.stars, b.review.stars => (a.review.stars + b.review.stars), 0) / review.stars.length;
        });
    };

我叫它的方式总是有语法错误..。

代码语言:javascript
复制
<div>
<p className="totalReviewsTally">Average: {getAverage(reviews.stars)} {reviews.length}</p>
</div>

我的组件文件

header.js

代码语言:javascript
复制
import React, {useState, useEffect} from "react";
import './index.css';
import './images/gup_logo.svg';
import './images/gup_logo_text.svg';
import './images/mapMarker.svg';
import './images/solidStar.svg';
import './images/emptyStar.svg';
import './images/halfStar.svg';
import './images/makeFaveShop.svg';
import './images/unFaveShop.svg';
import './images/contactButton.svg';
import './images/shopCart.svg';
import { Link } from "@reach/router";


const Header = (props) => {

    const [shopOwnerInfo, setShopOwnerInfo] = useState([]);
    const [reviews, setReviews] = useState([]);

    useEffect(() => {
        const getJsonOwnerData = async () => {
            const response = await fetch(`http://www.localhost:3000/shopOwner/1`);
            const responseShopOwner = await response.json();
            setShopOwnerInfo(responseShopOwner);
        };

        const getReviews = async () => {
            const response = await fetch(`http://www.localhost:3000/reviews`);
            const reviewsResponse = await response.json();
            setReviews(reviewsResponse);
        };

        getReviews();
        getJsonOwnerData();

    }, []);

    const getAverage = (reviews) => {
        reviews.map((review) => {
            return review.stars.reduce((a.review.stars, b.review.stars => (a.review.stars + b.review.stars), 0) / review.stars.length;
        });
    };


    return (
        <div className="appHeader">
            <div className="logoLeft">
                <Link to="/">
                <img src={window.location.origin + '/images/gup_logo.svg'} alt="some company logo" className="circleLogo"/>
                </Link>
                <p className="shopOwnerTitle">SHOP OWNER</p>
                <p className="shopOwnerName">{shopOwnerInfo.name}</p>
                <a href="mailto: email@email.com"><img src={window.location.origin + '/images/contactButton.svg'} alt="contact button" className="contactButton"/></a>
            </div>
            <div className="headerLeftSide">
                <Link to="/">
                <img src={window.location.origin + '/images/gup_logo_text.svg'} alt="some company logo" className="textLogo"/>
                </Link>
                <div className="locationLine"><img src={window.location.origin + '/images/mapMarker.svg'} alt="map marker for city, state" className="mapMarker"/>
                <p className="cityState">{shopOwnerInfo.shopLocation}</p></div>

                <div className="salesLine">
                    <p className="saleNumber">0 Sales</p>
                </div>

                <div className="starsLine">
                        

                <div>
                    <p className="totalReviewsTally">Average: {getAverage(reviews.stars)} {reviews.length}</p>
                </div>


                </div>

                <div className="faveShop">
                    <img src={window.location.origin + '/images/unFaveShop.svg'} alt="Click heart to make this your favorite shop" className="faveShopOpenHeart"/>
                    <p className="faveShopTally">Favorite Shop (0)</p>
                </div>
            </div>

            <Link to="/shoppingCart" className="unstyleLink">
            <div className="headerRightSide">
                <div className="countInCart">
                {props.cartCount} 
                </div>
                <img src={window.location.origin + '/images/shopCart.svg'} alt="shopping cart" className="shopCart"/>
            </div>
            </Link>
        </div>
    );
};

export default Header;

我在src文件夹中的db.json文件

代码语言:javascript
复制
{
  "shopOwner": [
    {
      "id": 1,
      "shopName": "Some Company",
      "title": "Owner",
      "name": "mr. owner",
      "shopLogo": "gup_logo.svg",
      "shopLogoText": "gup_logo_text.svg",
      "shopLocation": "Somewhere, SomeState",
      "shopSales": 0,
      "faveShop": 0,
      "contactEmail": "someEmail@email.com",
      "contactNumber": 2155551212,
      "returnPolicy": "No returns accepted due to Covid-19",
      "exchangePolicy": "Exchanges are only permitted if damaged in shipping",
      "shipping": "USPS",
      "shippingZipCode": 11111,
      "estimatedShipTime": "5 - 7 business days after order is placed",
      "paymentOptions": "paypal"
    }
  ],
  "reviews": [
    {
      "text": "So cute, love it!",
      "stars": 4,
      "id": 1
    },
    {
      "text": "Cute for handmade, but it faded in the first wash.",
      "stars": 2,
      "id": 2
    },
    {
      "text": "Great gift for my BFF's first baby.",
      "stars": 5,
      "id": 3
    }
  ],
  "shopItem": [
    {
      "id": 1,
      "name": "10 Fingers 10 Toes I'm Good",
      "itemType": "Infant Onesie",
      "size": "3-6 months",
      "price": "$15.00",
      "quantity": 1,
      "materialColor": "white",
      "materialType": "100% Cotton",
      "printColor": "black, red",
      "picture": "10FingersPic.jpg",
      "description": "Unisex Infant Short Sleeve Onesie with silk screen printed graphics"
    },
    {
      "id": 2,
      "name": "1/2 Pint",
      "itemType": "Infant Onesie",
      "size": "3-6 months",
      "price": "$15.00",
      "quantity": 1,
      "materialColor": "white",
      "materialType": "100% Cotton",
      "printColor": "blue",
      "picture": "halfPintPic.jpg",
      "description": "Infant Short Sleeve Onesie with silk screen printed graphics for boy"
    },
    {
      "id": 3,
      "name": "offspring",
      "itemType": "Infant Onesie",
      "size": "3-6 months",
      "price": "$15.00",
      "quantity": 1,
      "materialColor": "white",
      "materialType": "100% Cotton",
      "printColor": "orange",
      "picture": "offspringPic.jpg",
      "description": "Unisex Infant Short Sleeve Onesie with silk screen printed graphics"
    },
    {
      "id": 4,
      "name": "locally grown",
      "itemType": "Infant Onesie",
      "size": "3-6 months",
      "price": "$15.00",
      "quantity": 1,
      "materialColor": "yellow",
      "materialType": "100% Cotton",
      "printColor": "blue, green",
      "picture": "locallyGrownPic.jpg",
      "description": "Unisex Infant Short Sleeve Onesie with silk screen printed graphics"
    },
    {
      "id": 5,
      "name": "Man Symbol",
      "itemType": "Infant Onesie",
      "size": "3-6 months",
      "price": "$15.00",
      "quantity": 1,
      "materialColor": "white",
      "materialType": "100% Cotton",
      "printColor": "green",
      "picture": "greenManPic.jpg",
      "description": "Infant Short Sleeve Onesie with silk screen printed graphics for boy"
    },
    {
      "id": 6,
      "name": "locally grown",
      "itemType": "Infant Onesie",
      "size": "3-6 months",
      "price": "$15.00",
      "quantity": 1,
      "materialColor": "white",
      "materialType": "100% Cotton",
      "printColor": "blue, green",
      "picture": "locallyGrownPicWhite.jpg",
      "description": "Unisex Infant Short Sleeve Onesie with silk screen printed graphics"
    }
  ],
  "shoppingCart": [
    {
      "id": "",
      "name": "",
      "itemType": "",
      "size": "",
      "price": "",
      "quantity": "",
      "materialColor": "",
      "materialType": "",
      "printColor": "",
      "picture": "",
      "description": ""
    },
    {
      "promocode": "",
      "subtotal": "",
      "shippingCost": "",
      "estimateTax": "",
      "estimatedTotal": ""
    }
  ],
  "checkout": [
    {
      "id": "",
      "name": "",
      "itemType": "",
      "size": "",
      "price": "",
      "quantity": "",
      "materialColor": "",
      "materialType": "",
      "printColor": "",
      "picture": "",
      "description": ""
    },
    {
      "subtotal": "",
      "shippingCost": "",
      "zipcodeTax": "",
      "actualTotal": ""
    }
  ]
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-12-03 08:09:58

简单的方法一步一步地处理。

代码语言:javascript
复制
const getAverage = (reviews) => {
    let TotalStars = reviews.reduce((prev, curr) => (curr.stars + prev), 0)
    // TotalStars is 3.6666 
    // below use any one of them averageStars
    // let averageStars = Math.round(TotalStars/reviews.length);  // output 4
    // let averageStars = Math.floor(TotalStars/reviews.length);  // output 3
    let averageStars = Math.floor((TotalStars/reviews.length)*10)/10;// output 3.6
    return averageStars;
};

<div>
    <p className="totalReviewsTally">Average: {getAverage(reviews)} {reviews.length}</p>
</div>
票数 0
EN

Stack Overflow用户

发布于 2020-12-03 04:47:43

您忘记了returngetAverage中的评论,我试图解决一些问题,如果这仍然不起作用,请告诉我。

根据你的评论

评论={“文本”:“如此可爱,爱它!”,“星星”:4,"id":1 },{“文本”:“手工制作的可爱,但它在第一次洗的时候就褪色了。”,“星星”:2,"id":2 },{“文本”:“给我的BFF的第一个孩子的礼物”,“星星”:5,"id":3}。

代码语言:javascript
复制
const getAverage = (reviews) => {
   return Math.round(reviews.reduce((acc, curr) => (acc + curr.stars), 0) / reviews.length));
};
代码语言:javascript
复制
    <div>
      <p className="totalReviewsTally">Average: { getAverage(reviews) } {reviews.length}</p>
    </div>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65118500

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档