【发布时间】:2019-06-07 15:25:01
【问题描述】:
我尝试编写代码的屏幕有一个条件渲染,显示是否存在任何事件。如果数组中有事件,那么它应该通过 map() 运行并将所有事件显示为列表。
但是当数组中没有值时,map() 仍然会执行并且我得到一个错误“TypeError: Cannot read property 'map' of null”。
因为我是 React 和 React Native 的初学者,所以我做不了什么!
class Home extends Component{
constructor(props) {
super(props);
this.state = {
events: []
}
}
componentDidMount(){
this.getDataFromStorage('Oh123456');
}
async getDataFromStorage(key){
await AsyncStorage.getItem(key).then((res) => {
res = JSON.parse(res);
this.setState({ events: res });
});
}
render() {
const noEventsFound = (
<View>
<Heading>
<H1>No Events Found!</H1>
</Heading>
</View>
);
const loadAllEventsNow = this.state.events.map((event) => (
<OhList eventName={event.name} />
));
return (
<ImageBackground source={backgroundImage} style={styles.backgroundImage}>
<View style={styles.container}>
{ !this.state.events ? noEventsFound : loadAllEventsNow }
</View>
<View>
<OhButton color="#7BE78A" onPress={() => this.props.navigation.navigate('Register')}>CREATE AN EVENT</OhButton>
</View>
</ImageBackground>
);
}
}
我希望屏幕在数组中没有事件时在屏幕上显示“未找到事件”,如果有任何事件,则显示事件列表。
【问题讨论】:
-
请添加您的示例 json 数据
-
感谢您的回复!这是示例 json 数据。 events = [{ name: "Graduation", date: "Dec 2", time: "10AM", hosts: "John", active: true, }];
标签: arrays react-native conditional-rendering