反应本地渲染foreach循环

时间:2020-03-18 07:24:49

标签: react-native ecmascript-6

我在render块内运行了forEach,它在 控制台,但文本标记未显示在输出中。

出什么问题了?

import React from "react";
import { StyleSheet, Text, View } from "react-native";

class Lotto extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      count: 6,
      maxNum: 45
    };

    this.lottoSet = this.createLottoNumber();
  }

  createLottoNumber() {
    let lottoSet = new Set();
    let rNum;

    for (let i = 0; i < this.state.count; i++) {
      rNum = Math.round(Math.random() * (this.state.maxNum * 1) + 1);
      if (lottoSet.has(rNum)) i--;
      else lottoSet.add(rNum);
    }

    return lottoSet;
  }

  render() {
    return (
      <View style={styles.container}>
        {this.lottoSet.forEach(n => {
          console.log(`<Text style={styles.item}>${n.toString()}</Text>`);
          return <Text style={styles.item}>{n.toString()}</Text>;
        })}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#333",
    flexDirection: "row",
    paddingTop: "10%",
    justifyContent: "center"
  },
  item: {
    color: "#fff",
    textAlign: "center",
    width: "100px"
  }
});

export default Lotto;

2 个答案:

答案 0 :(得分:2)

您必须使用map来渲染元素。

render() {
    return (
      <View style={styles.container}>
        {this.lottoSet.map(n => (
          <Text key={n.toString()} style={styles.item}>{n.toString()}</Text>
        ))}
      </View>
    );
  }

React是声明性的,并采取视图状态的声明进行渲染,map将构建一个声明的,不变的视图状态。鉴于使用forEach可能会在render方法之外创建副作用,因此不支持。

答案 1 :(得分:1)

forEach不返回值,而是代表在每个数组元素上执行副作用。 相反,您正在寻找map

  <View style={styles.container}>
    {this.lottoSet.map(n => {
      console.log(`<Text style={styles.item}>${n.toString()}</Text>`);
      return <Text key={n.toString()} style={styles.item}>{n.toString()}</Text>;
    })}
  </View>

此外,请注意,我向每个key元素添加了一个Text道具,您可以在这里阅读有关内容:https://reactjs.org/docs/lists-and-keys.html

顺便说一句,您在构造函数中调用过一次createLottoSet的事实,这意味着不会在每次状态更改时都生成它。