Render Content Dynamically from an array map funct

2020-02-05 01:40发布

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);

}

}

4条回答
够拽才男人
2楼-- · 2020-02-05 01:52

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>
    );
  })
 );
}
查看更多
狗以群分
3楼-- · 2020-02-05 01:55
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.

查看更多
不美不萌又怎样
4楼-- · 2020-02-05 02:13

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>
  )
}
查看更多
霸刀☆藐视天下
5楼-- · 2020-02-05 02:17

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

查看更多
登录 后发表回答