【问题标题】:How to write conditional rendering with map() on an array if there is no values in the array?如果数组中没有值,如何在数组上使用 map() 编写条件渲染?
【发布时间】: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


【解决方案1】:

假设 this.state.events 是一个可以替换的数组

<View style={styles.container}>
      { !this.state.events ? noEventsFound : loadAllEventsNow } 
</View>

用这个

<View style={styles.container}>
      { Array.isArray(this.state.events) && this.state.events.length < 1 ? noEventsFound : loadAllEventsNow } 
</View>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 2020-04-03
    • 2020-10-10
    • 2016-03-06
    • 2019-04-07
    • 2020-09-17
    相关资源
    最近更新 更多