react native render foreach loop



我在渲染块内运行了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是声明性的,并采用视图状态的声明来呈现,map将构建一个声明的、不可变的视图状态。而使用forEach可能会在渲染方法之外产生副作用,因此不受支持。

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一次,这意味着它不会在每次状态更改时生成。

最新更新