最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React .trim() is not a function - Stack Overflow

programmeradmin0浏览0评论

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
 );
发布评论

评论列表(0)

  1. 暂无评论