admin管理员组

文章数量:1356735

My application has a landing page with two ponents in two separate tabs.

The code from the first ponent that is causing the crash looks like this:

for (let key in linegraphdata) {
  linegraphdata[key].price = Number(
    linegraphdata[key].price.trim().slice(1)
  );
  linegraphdata[key].month = parseDate(linegraphdata[key].month);
}

When I load into my application initially it doesn't crash, loads the data from the first tab fine. I'll click into the second tab and when I eventually click back the whole application crashes and the log gives me this error:

Uncaught TypeError: linegraphdata[key].price.trim is not a function

It must have something to do with how React handles refreshing ponents once already rendered, could anyone help me figure it out please :)

My application has a landing page with two ponents in two separate tabs.

The code from the first ponent that is causing the crash looks like this:

for (let key in linegraphdata) {
  linegraphdata[key].price = Number(
    linegraphdata[key].price.trim().slice(1)
  );
  linegraphdata[key].month = parseDate(linegraphdata[key].month);
}

When I load into my application initially it doesn't crash, loads the data from the first tab fine. I'll click into the second tab and when I eventually click back the whole application crashes and the log gives me this error:

Uncaught TypeError: linegraphdata[key].price.trim is not a function

It must have something to do with how React handles refreshing ponents once already rendered, could anyone help me figure it out please :)

Share Improve this question asked Aug 22, 2018 at 15:05 MrShedfordMrShedford 1371 gold badge3 silver badges12 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 2

You're setting what was a string to a number, and numbers don't have the trim() method on them. That's why it works the first time (when it's a string) and not the second time around:

array[key] = Number(array[key].trim());

So that code must be executing more than once.

linegraphdata[key].price is either null or not a string.

If there is a value, you can try using linegraphdata[key].price.toString().trim().slice(1)

You can check that price is a string with this ternary. If it's not a string it will set the value to -1

linegraphdata[key].price = Number(
    typeof linegraphdata[key].price == 'string' ? linegraphdata[key].price.trim().slice(1) : -1
 );

本文标签: javascriptReact trim() is not a functionStack Overflow