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

javascript - split() method on state value in React Native - Stack Overflow

programmeradmin5浏览0评论

I've got town value (in an object) like:

75000 - Paris Ile-de-France

I'm trying to get the second part of my town state value using the split method:

<Text>{this.state.town.split("-")[1].trim() || ''}</Text>

But it seems split method is taken as an element of the object. I've got this error:

Cannot read property 'split' of undefined.

Any idea?

UPDATE :

Ok, it's undefined at start point, before I update the state of town.

Now I try to put a condition before it tries to split my string, but I fail. I'm doing this, but it returns an unexpected token:

<Text style={styles.selectedTown}>{
      return (this.state.town !== {}) ? this.state.town.split('-')[0].trim() : '';
    }</Text>

I've got town value (in an object) like:

75000 - Paris Ile-de-France

I'm trying to get the second part of my town state value using the split method:

<Text>{this.state.town.split("-")[1].trim() || ''}</Text>

But it seems split method is taken as an element of the object. I've got this error:

Cannot read property 'split' of undefined.

Any idea?

UPDATE :

Ok, it's undefined at start point, before I update the state of town.

Now I try to put a condition before it tries to split my string, but I fail. I'm doing this, but it returns an unexpected token:

<Text style={styles.selectedTown}>{
      return (this.state.town !== {}) ? this.state.town.split('-')[0].trim() : '';
    }</Text>
Share Improve this question edited Jun 10, 2016 at 13:50 Xavier C. asked Jun 10, 2016 at 13:30 Xavier C.Xavier C. 1,8174 gold badges25 silver badges40 bronze badges 4
  • 3 this.state.town.name is undefined – Pranav C Balan Commented Jun 10, 2016 at 13:31
  • Sorry I made corrections. – Xavier C. Commented Jun 10, 2016 at 13:32
  • 1 What does your state look like at that point in time? The error would seem to indicate that there's no town property inside of your state. – ajm Commented Jun 10, 2016 at 13:37
  • 3 Again, this means that town is undefined. Please show that code that you use to intialize this.state. – Cobus Kruger Commented Jun 10, 2016 at 13:37
Add a ment  | 

1 Answer 1

Reset to default 2

There is a difference between undefined and defined as an empty object. Try this:

<Text style={styles.selectedTown}>{
      (this.state.town !== undefined) ? this.state.town.split('-')[0].trim() : ''
    }</Text>
发布评论

评论列表(0)

  1. 暂无评论