Render Content Dynamically from an array map function in React Native

╄→гoц情女王★ 提交于 2019-11-27 02:33:02

问题


I'm trying to get data from an array and using map function to render content. Look at

**{this.lapsList()}** 

and the associated

**lapsList()** 

function to understand what I'm trying to do. The result is nothing is displaying (Views under view, etc.) Here is my simplified code:

class StopWatch extends Component {

constructor(props) {
  super(props);

  this.state = {
    laps: []
  };
}

render() {
  return (
    <View style={styles.container}>
        <View style={styles.footer}>
          <View><Text>coucou test</Text></View>
          {this.lapsList()}
        </View>
    </View>
  )
}

lapsList() {

    this.state.laps.map((data) => {
      return (
        <View><Text>{data.time}</Text></View>
      )
    })

}

_handlePressLap() {

  console.log("press lap");

  if (!this.state.isRunning) {

    this.setState({
      laps: []
    })

    return

  }

  let laps = this.state.laps.concat([{'time': this.state.timeElapsed}]);

  this.setState({
      laps: laps
  })

  console.log(laps);

}

}


回答1:


Don't forget to return the mapped array , like:

lapsList() {

    return this.state.laps.map((data) => {
      return (
        <View><Text>{data.time}</Text></View>
      )
    })

}

Reference for the map() method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map




回答2:


Try moving the lapsList function out of your class and into your render function:

render() {
  const lapsList = this.state.laps.map((data) => {
    return (
      <View><Text>{data.time}</Text></View>
    )
  })

  return (
    <View style={styles.container}>
      <View style={styles.footer}>
        <View><Text>coucou test</Text></View>
        {lapsList}
      </View>
    </View>
  )
}



回答3:


you forgot the return at the beginning of the function lapsList()

lapsList() {
 render(
  this.state.laps.map((data) => {
    return (
      <View><Text>{data.time}</Text></View>
    );
  })
 );
}



回答4:


lapsList() {

    return this.state.laps.map((data) => {
      return (
        <View><Text>{data.time}</Text></View>
      )
    })
}

You forgot to return the map. this code will resolve the issue.



来源:https://stackoverflow.com/questions/37446029/render-content-dynamically-from-an-array-map-function-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!