Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an array of objects. I want to update one property of every object in the array inside a function.

I declare a function outside render:

const computePiePercentages = function(pieChartData, remainingBudget){
  var denominator = 1600;
  if(remainingBudget > 0){
    denominator = 1600 - remainingBudget
  }


  return pieChartData.map((val, j) => {
    val.y = Number((val.y / denominator).toFixed(1)) * 100

  });


  };

I am still very new to react - I know that pieChartData.map((val, j) allows me to loop through the objects in my array. I thought by return pieChartData.map((val, j) I would be returning the updated array. However, that doesn't appear to be the case. I am currently getting Cannot read property 'x' of undefined for scale.js (I dont even know this file)

I call the function here:

render() {

    const { data, remainingBudget, pieChartData, outOfBudget, answeredQuestions } = this.state;

    const questions = data.questions;
    return (
      <div>
          {answeredQuestions == 1 &&
          <div>
            <VictoryPie
              colorScale = "blue"
              data = {computePiePercentages(pieChartData, remainingBudget)}
              //data = {this.state.pieChartData}
              labels= {d => `${d.x}: ${d.y}%`}
              style={{ parent: { maxWidth: '50%' } }}
              />
            {outOfBudget.length > 0 &&
              <div>
              <Table>
                <th>Out of Budget</th>
                < BrokeBudget
                  outOfBudget={outOfBudget}
                  />
              </Table>
              </div>
            }
          </div>
        }
      </div>
    );
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
204 views
Welcome To Ask or Share your Answers For Others

1 Answer

The map() method creates a new array with the results of calling a provided function on every element in the calling array. So you must return a value from callback function for the new array, as it doesn't modify existing array.

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results.

So below should fix the issue for you :

const computePiePercentages = function(pieChartData, remainingBudget){
  var denominator = 1600;
  if(remainingBudget > 0){
    denominator = 1600 - remainingBudget
  }


  return pieChartData.map((val, j) => {
    let newVal = Object.assign({}, val);
    newVal.y = Number((newVal.y / denominator).toFixed(1)) * 100
    return newVal;
  });


  };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...