2017-05-26 74 views
0

我正在使用反應原生來構建我的應用程序。以下是我用來顯示「標籤」列表的代碼。所以代碼被用來隱藏除第2個之外的所有標籤,並且會出現「加載更多」鏈接。點擊加載更多鏈接應該顯示其餘的標籤。但是代碼崩潰了。React Native JSX:設置狀態導致應用程序崩潰

this.state = { 
    visibleCount: 2, 
}; 

<TextLink onPress={() => { 
    this.setState({visibleCount: mealTags.length}); 
    }} 
</TextLink> 

我正在使用更改狀態來顯示標籤。任何人都可以告訴我出了什麼問題,以及如何更新它?

export function MealTagsSection(props: MealTagsProps) { 
    let {mealTags} = props; 
    let loadMoreLink; 

    if (mealTags.length > 2) { 
    loadMoreLink = (
     //THIS CAUSES THE APP TO CRASH 
     <TextLink onPress={() => { 
     this.setState({visibleCount: mealTags.length}); 
     }} 
     > 
     load more... 
     </TextLink> 
    ); 
    } else { 
    loadMoreLink = null; 
    } 

    this.state = { 
    visibleCount: 2, 
    }; 

    return (
    <View style={styles.mealTagsContainer}> 
     { 
     mealTags.slice(0, this.state.visibleCount).map((mealTag) => { 
      let tagStyle = ''; 
      if (mealTag.category === 1) { 
      tagStyle = styles.tag_healthy; 
      } else { 
      tagStyle = styles.tag_improve; 
      } 
      return (
      <View style={tagStyle}> 
       <Text style={styles.tagText}>{mealTag.description}</Text> 
      </View> 
     ); 
     }) 
     } 
     {loadMoreLink} 
    </View> 
); 
} 

我得到的錯誤是這樣的: ***終止應用程序由於未捕獲的異常「RCTFatalException:未處理的異常JS:t.setState不是一個函數。 (在't.setState({visibleCount:n.length})','t.setState'未定義)',原因:'未處理的JS異常:t.setState不是函數。 (In't.setState({visi ...,stack:onPress @ 439:2034

+2

不要直接發生變異狀態,調用'this.setState' – Li357

+0

感謝@AndrewLi,改變我收到此錯誤後:2017年5月26日11 :30:24.419實現[31978:2275669] ***終止應用程序,由於未捕獲的異常'RCTFatalException:未處理的JS異常:t.setState不是函數(在't.setState({visibleCount:n.length})' ,'t.setState'未定義)',原因:'未處理的JS異常:t.setState不是函數。 't.setState({visi ...,stack: onPress @ 439:2034 – Zhen

回答

2

你的MealTagsSection是一個功能組件,React功能組件不一定包含本地狀態,如果想要當地的一個狀態,那麼你應該讓一個類成分

export class MealTagsSection extends Component { 
    constructor() { 
    super(); 
    this.state = { visibleCount: 2 }; 
    } 

    render() { 
    let { mealTags } = this.props; 
    let loadMoreLink; 

    if (mealTags.length > 2) { 
     loadMoreLink = 
     (
      <TextLink 
      onPress={() => { 
       this.setState({ visibleCount: mealTags.length }); 
      }} 
      > 
      load more... 
      </TextLink> 
     ); 
    } else { 
     loadMoreLink = null; 
    } 

    return (
     <View style={styles.mealTagsContainer}> 
     {mealTags.slice(0, this.state.visibleCount).map(mealTag => { 
      let tagStyle = ""; 
      if (mealTag.category === 1) { 
      tagStyle = styles.tag_healthy; 
      } else { 
      tagStyle = styles.tag_improve; 
      } 
      return (
      <View style={tagStyle}> 
       <Text style={styles.tagText}>{mealTag.description}</Text> 
      </View> 
     ); 
     })} 
     {loadMoreLink} 
     </View> 
    ); 
    } 
} 
相關問題