2017-10-05 39 views
0

我有一個項目的列表,我想只有其中一個在任何給定的時間突出顯示。我寫了下面的代碼:空值不是一個對象,當評估this.state

constructor(props) { 
    super(props); 
    this.setState({indexHighlighted: 0}); 
} 

selectItem = (i) => { 
    this.setState({indexHighlighted: i}); 
} 

checkIfHighlighted = (i) => { 
    i == this.state.indexHighlighted; 
} 

render() { 
    return ( 
     <FlatList 
      data={myData} 
      renderItem={ ({item}) => 
       <TouchableHighlight onPress={this.selectItem(item["indexNr"])}> 
        <ShoppingListItem 
         key={item["indexNr"]} 
         highlighted = {this.checkIfHighlighted(item["indexNr"])} 
         orderInList={item["indexNr"]} /> 
       </TouchableHighlight> 
      } 
      keyExtractor = {(item, index) => index} 
     /> 
    ); 
} 

當我運行這段代碼,我得到 null is not an object (evaluating '_this.state.indexHighlighted')

爲什麼會this.statenull?如果我從構造函數中設置它,它可以是null

如果是,那我該如何在適當的時候初始化它,以免錯誤出現?

+3

在你的構造初始化像'this.state =狀態{indexHighlighted:0};',而不是使用'setState'。 –

+0

您還需要使用大括號函數語法'返回i == this.state.indexHighlighted;'。你錯過了'return'關鍵字。 –

+1

@Prakashsharma你應該寫一個答案..唯一知道他們在說什麼的人。 – floor

回答

-2

在構造函數中,你應該使用這個語法:

constructor(props) { 
    super(props); 
    this.state = { 
     indexHighlighted: 0 
    }; 
    } 
2

你有2個語法錯誤。

一個是你沒有正確的設置狀態。其次,您正在執行該功能,而不是將其作爲屬性傳遞。

constructor(props) { 
    super(props); 
    this.state = {indexHighlighted: 0}; 
} 

<TouchableHighlight onPress={() => this.selectItem(item["indexNr"])}> 
    // ... 
<TouchableHighlight /> 
0

必須綁定你的函數在constructor,如果你想發送的參數給你的函數,你應該定義在JSX外部功能。你也可以使用checkIfHighlighted fucn。

constructor(props) { 
    super(props); 
    this.state = { 
     indexHighlighted: 0 
    }; 
    this.checkIfHighlighted = this.checkIfHighlighted.bind(this); 
    this.selectItem = this.selectItem.bind(this); 
     } 

... 
checkIfHighlighted(){ 
    return i == this.state.indexHighlighted; 

} 
... 

JSX:

<TouchableHighlight onPress={()=>{this.selectItem(item["indexNr"])}}> 
        <ShoppingListItem 
         key={item["indexNr"]} 
         highlighted = {this.checkIfHighlighted(item["indexNr"])} 
         orderInList={item["indexNr"]} /> 
       </TouchableHighlight> 
+0

無需綁定。 OP正在使用箭頭功能。 –

+0

我認爲'this'會在未綁定到selectItem函數時引用undefined。 –

+2

如果你使用箭頭功能,那麼你不需要綁定。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions –

相關問題