【问题标题】:react native render foreach loop反应原生渲染 foreach 循环
【发布时间】:2020-06-29 06:46:03
【问题描述】:

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

【问题讨论】:

标签: react-native ecmascript-6


【解决方案1】:

您必须改用地图来渲染元素。

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

React 是声明式的,需要声明视图状态来渲染,map 将构建一个声明的、不可变的视图状态。而使用 forEach 可能会在渲染方法之外产生副作用,因此不受支持。

【讨论】:

    【解决方案2】:

    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>
    

    另外,请注意,我为每个 Text 元素添加了一个 key 属性,您可以在此处阅读:https://reactjs.org/docs/lists-and-keys.html

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

    【讨论】:

      猜你喜欢
      • 2018-02-02
      • 2020-05-05
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      • 2017-02-10
      • 2020-04-22
      • 1970-01-01
      相关资源
      最近更新 更多