react-native - react 原生渲染 foreach 循环

标签 react-native ecmascript-6

我在渲染块内运行了 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;

最佳答案

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

render() {
    return (
      <View style={styles.container}>
        {this.lottoSet.map(n => (
          <Text key={n.toString()} style={styles.item}>{n.toString()}</Text>
        ))}
      </View>
    );
  }
React 是声明式的,需要声明 View 状态来渲染,map 将构建一个声明的、不可变的 View 状态。而使用 forEach 有可能在渲染方法之外产生副作用,因此不受支持。

关于react-native - react 原生渲染 foreach 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60735050/

相关文章:

javascript - React Native,导航

react-native - 在 React Native v0.46 中使用动画隐藏和显示 View 。

javascript - ES6 使用构造函数参数设置此属性

javascript - es6 中私有(private)变量(前导下划线)的等价物?

typescript - 在 TypeScript 中合并两个对象,无需检查键是否存在

java - React-Native 无法在 Android 上构建

android - React Native : Undefined is not a function(evaluating this. Prop ...)

reactjs - 使用 React 如何在每次选中复选框时附加到字符串并显示在另一个输入文本字段中

javascript - requestAnimationFrame 太快

javascript - d3 v4 + React + es6 + crossfilter : Selection. exit().remove() 不起作用