我知道这已被多次询问,但提到的解决方案似乎都不适合我。
import React, { Component } from "react";
import { Text, View, StyleSheet, FlatList } from "react-native";
import { Fonts, FontSize, Colors } from "../../constants";
const styles = StyleSheet.create({
chat: {
flex: 1,
backgroundColor: "#EDECEA",
display: "flex",
alignItems: "center"
//justifyContent: "center"
},
introText: {
...Fonts.bold,
fontSize: FontSize.s,
maxWidth: 200,
lineHeight: 18.5,
textAlign: "center",
marginTop: 100,
marginBottom: 100,
color: "rgba(28, 28, 29, 0.5)"
},
smallText: {
...Fonts.normal
},
servicePackContentContainer: {
position: "absolute",
backgroundColor: "red",
shadowColor: "gray",
shadowOffset: {
width: 0,
height: 0.5
},
shadowRadius: 1,
borderBottomWidth: 1,
borderBottomColor: "rgba(217, 216, 215, 0.5)"
},
serviceTitleStyle: {
fontSize: 22,
...Fonts.bold,
textAlign: "center",
color: Colors.white
},
serviceDescStyle: {
textAlign: "center",
...Fonts.bold,
fontSize: 14,
marginHorizontal: 10,
color: Colors.white
}
});
class MyOwnList extends Component {
constructor(props) {
super(props);
this.state = {
formattedData: [],
data: [
{ id: 0, title: "Option0"},
{ id: 1, title: "Option1"},
{ id: 2, title: "Option2"},
{ id: 3, title: "Option3"},
{
id: 4,
title: "Option4"
},
{ id: 5, title: "Option5"},
{ id: 6, title: "Option6"},
{ id: 7, title: "Option7"},
{ id: 8, title: "Option8"},
{ id: 9, title: "Option9"}
]
};
}
componentWillMount() {
this.generateTheList();
}
getRandomInt = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
async generateTheList() {
let len = this.state.data.length;
for (let i = 0; i < 4; i++) {
let randomIndex = this.getRandomInt(0, len);
await this.setState({
formattedData: [
...this.state.formattedData,
this.state.data[randomIndex]
]
});
}
}
renderServices = item => {
return (
<View style={styles.servicePackContentContainer}>
<Text style={styles.serviceTitleStyle}> {item.title}</Text>
</View>
);
};
render() {
return (
<View style={styles.chat}>
<Text style={styles.introText}>
Ask for our help and we will answer as soon as possible
<Text style={styles.smallText}> (English only)</Text>
</Text>
<FlatList
ref={component => {
this.listView = component;
}}
data={this.state.formattedData}
renderItem={this.renderServices}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
}
export default MyOwnList;
基本上,每当我来到这个屏幕时,我想显示 4 个随机选项。由于 setState 是异步的,我在方法中添加了 async 和 await ,以便当状态更改时它会反映在屏幕上。这确实有效,但有时我得到
undefined 不是对象评估('item.title')。