简体   繁体   English

对于React-native中的Loop,仅呈现index [0]

[英]For Loop in react-native render only index[0]

I don't understand why my loop render me only index[0] in my loop.... I have à state that's an array : 我不明白为什么我的循环在循环中只给我index [0]……。我有à状态,它是一个数组:

this.state = {
      days: ["Lundi","Mardi","Mercredi"]
    } 

And i want to render each day in my component: 我想在组件中渲染每一天:

render(){
    for (let i = 0; i < this.state.days.length; i++) {
      console.log(this.state.days[i]);
      return (

        <Text>{this.state.days[i]}</Text>

      );

Any ideas ?? 有任何想法吗 ??

您可以使用return命令中断循环,因此该循环仅输入一次

Because you are returning within your for loop which breaks the loop 因为您要在for循环中返回,这会中断循环

You are best to use map 您最好使用地图

render() {
    return (
      <div>
        { 
          array.map(day => {
            return (
              <p>{day}</p>
            );
          })
        }
      </div>
    );
  }

Your render method should be like this: 您的渲染方法应如下所示:

render(){
    return(
       <View>
         {this.state.days.map((item, index) => {
             <Text>{item}</Text>
           }
         )}
       </View>
    )

}

.render must return a single root node. .render必须返回单个根节点。 This way you're returning multiple nodes. 这样,您将返回多个节点。

You need to do something like (wrap your content in a div) 您需要做类似的事情(将内容包装在div中)

  render() {
    return (
      <div>
        {
          this.state.days.map(d => <Text>{d}</Text>)
        }
      </div>
    );
  }
 render() {
        this.state = {
            days: ["jan","feb","Mar"]
          } 
        return (
          <View style={styles.container}>
              { 
              this.state.days.map(d => <Text>{d}</Text>)
            }
            </View>
        )
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM