2017-10-19 82 views
0

我想要將列表交替呈現爲網格中的兩列。我打算在組件狀態中使用標誌變量,並在每次返回CardDetail時更改其值。反應本機渲染組件或者通過使用狀態

我註釋掉了this.changeState()聲明,因爲它們看起來不像預期的那樣工作。

請幫我理解這一點,我是新的React/React Native。 在此先感謝。

renderAlbums() { 
    return this.state.albums.map(album =>{ 
     this.rend2(album) 
    } 
    ); 
    } 
rend2(album){ 
if(this.state.flag === 0) 
{ 
    //this.changeState(); 
    return (<CardDetail key={album.title} album={album} />); 
} 
else 
{ 
//this.changeState; 
return (<View />); 
} 
} 

changeState(){ 
    if(this.state.flag === 0) 
{ 
this.setState({flag:1}); 
} 
else 
{ 
    this.setState({flag:0}) 
} 
} 

    render() { 
    console.log(this.state); 

    return (

     <ScrollView> 
     <Grid> 
     <Col>{this.renderAlbums()}</Col> 
     <Col>{this.renderAlbums()}</Col> 

     </Grid> 
     </ScrollView> 
    ); 
    } 
} 
+0

您正在使用和不使用圓括號觸發'changeState'。也許這是問題?另外,在每個渲染上調用'changeState'將會在代碼中產生無限循環。 – mersocarlin

+0

我在沒有括號的情況下調用'changeState'。改變了它。但仍然不起作用。模擬器變爲空白。所以要解決無限循環問題,我應該改變什麼? –

+0

我不明白你想要做什麼。你有兩個列表,每當'CardDetail'呈現時,你需要改變狀態? – mersocarlin

回答

1

我不認爲你需要在這種情況下改變狀態。只是參數傳遞給您的renderAlbums()方法,並用它來接列表中的所有其它專輯:

renderAlbums(col) { 
    return this.state.albums.map((album, index) => { 
    if (index % 2 == col) 
     return (<CardDetail key={album.title} album={album} />); 
    else 
     return (<View/>); 
    }); 
} 

然後在您的render()方法:

render() { 
    return (
    <ScrollView> 
     <Grid> 
     <Col>{this.renderAlbums(0)}</Col> 
     <Col>{this.renderAlbums(1)}</Col> 
     </Grid> 
    </ScrollView> 
); 
} 

此代碼尚未經過測試,但它應該工作。

1

也許改變你的方法一點點,並同時呈現兩列。那麼你可以在想要渲染的列之間切換CardDetail

return (
    <ScrollView> 
    <Grid> 
     {this.state.albums.map((album, index) => 
     <View key={index}> 
      <Col>{index % 2 === 0 
      ? <CardDetail key={album.title} album={album} /> 
      : <View /> 
      }</Col> 

      <Col>{index % 2 !== 0 
      ? <CardDetail key={album.title} album={album} /> 
      : <View /> 
      }</Col> 
     </View> 
     } 
    </Grid> 
    </ScrollView>