反应本机渲染组件或者通过使用状态

问题描述:

我想要将列表交替呈现为网格中的两列。我打算在组件状态中使用标志变量,并在每次返回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

我不认为你需要在这种情况下改变状态。只是参数传递给您的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> 
); 
} 

此代码尚未经过测试,但它应该工作。

也许改变你的方法一点点,并同时呈现两列。那么你可以在想要渲染的列之间切换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>