admin管理员组

文章数量:1424914

I don't understand why my loop render me only index[0] in my loop.... I have à state that's an array :

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

And i want to render each day in my ponent:

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 ??

I don't understand why my loop render me only index[0] in my loop.... I have à state that's an array :

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

And i want to render each day in my ponent:

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 ??

Share Improve this question asked Mar 12, 2018 at 9:41 E.DE.D 8913 gold badges17 silver badges36 bronze badges 2
  • 2 Hint, what does the return statement do? – Etheryte Commented Mar 12, 2018 at 9:43
  • Because of return statement. – Lalit Commented Mar 12, 2018 at 9:44
Add a ment  | 

5 Answers 5

Reset to default 4

You break the loop with the return mand, so it's enter only once to the loop

Because you are returning within your for loop which breaks the loop

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. This way you're returning multiple nodes.

You need to do something like (wrap your content in a 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>
        )
 }
}

本文标签: javascriptFor Loop in reactnative render only index0Stack Overflow