我知道这个问题已经被问过多次了,但是提到的所有解决方案似乎都不适合我。
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是异步的,因此我向方法添加了asyn并等待,以便在状态更改时将其反映在屏幕上。确实可以,但是有时我会得到
undefined不是评估对象('item.title')。
答案 0 :(得分:0)
您怎么为FlatList指定两次属性renderItem?
好像您忘记破坏了renderServices的参数:
renderServices = ({item}) => {
return (
<View style={styles.servicePackContentContainer}>
<Text style={styles.serviceTitleStyle}> {item.title}</Text>
</View>
);
};
答案 1 :(得分:0)
您使用了错误的语法。渲染项功能应为:
renderServices = ({index, item}) => {
return (
<View style={styles.servicePackContentContainer}>
<Text style={styles.serviceTitleStyle}> {item.title}</Text>
</View>
);};
您需要访问平面列表行的“项目”:({index,item})