最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - For Loop in react-native render only index[0] - Stack Overflow

programmeradmin3浏览0评论

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>
        )
 }
}
发布评论

评论列表(0)

  1. 暂无评论