0

Мне нужно сделать сумму exercises в компоненте Total, но показывает NaN

import React from 'react'
    
const Total = (props) => {
    return(
        <>
            <p>Number of exercises {props.numOfExercises.reduce(function(previousValue, currentValue) {
               return previousValue.exercises + currentValue.exercises;
            })}</p>
        </>
    )
}
    
export default Total;



import React from 'react'
import Total from "./components/Total";

const App = () => {
    const course = 'Half Stack application development'
    const contentText = [
        { part: 'Fundamentals of React', exercises: 10 },
        { part: 'Using props to pass data', exercises: 7 },
        { part: 'State of a component', exercises: 14 }
    ];

    return (
        <div>
            <Total numOfExercises={contentText} />
        </div>
    )
}

export default App;
4
  • 3
    После первой итерации reduce вторая итерация будет в previousValue содержать результат первой итерации — число 10+7=17, а у чисел не бывает никаких exercises, поэтому previousValue.exercises это undefined и undefined + 14 это получается NaN
    – andreymal
    3 авг 2020 в 16:22
  • @andreymal а если я меняю так {props.numOfExercises.reduce(function(previousValue, currentValue) { return previousValue.exercises + currentValue.exercises; },0)} чтобы для первой итерации было значение 0 то это тоже не меняет ничего.
    – dev2021
    3 авг 2020 в 16:28
  • 1
    Ну так причина та же самая: в первой итерации previousValue это число 0, а у чисел не бывает никакого exercises, поэтому previousValue.exercises это undefined и undefined+10 это тоже NaN и далее по аналогии
    – andreymal
    3 авг 2020 в 16:33
  • @andreymal поняла, спасибо!
    – dev2021
    3 авг 2020 в 16:48

1 ответ 1

3

Попробуйте так

<p>Number of exercises 
{props.numOfExercises.reduce(
    function(previousValue, currentValue) {
        return previousValue + currentValue.exercises;
    }, 0)
}</p>
3
  • Я попробовала сделать так с вашей подсказки и получилось! <p>Number of exercises {props.numOfExercises.reduce(function(previousValue, currentValue) { return previousValue + currentValue.exercises; },0)}</p> спасибо вам!
    – dev2021
    3 авг 2020 в 16:46
  • Исправил спс извините 3 авг 2020 в 16:48
  • @puzzelena Пометьте ответ галочкой, если данный ответ является решением вашей проблемы
    – E1mir
    3 авг 2020 в 17:16

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.