【问题标题】:Impossible to display the data after a get request react native获取请求反应原生后无法显示数据
【发布时间】:2020-03-18 11:26:40
【问题描述】:

我试图在我的 react-native 应用程序中显示餐厅的信息,这是通过我的数据库的 get 请求获得的。我获取数据没有问题,是显示问题。

在我的组件 RestaurantDetailScreen 中:

  componentDidMount() {
    this.getRestaurantInfo()
  }

  getRestaurantInfo = async () => {
    try {
      let res = await axios({
        method: 'get',
        url: `${environment.apiDevUrl}/restaurant/${this.state.restaurantId}`,
      })
      this.setState({
        restaurantInfo: res.data,
      })
      console.log(this.state.restaurantInfo.restaurant.nom);
    } catch (error) {
      console.error(error)
    }
  }

控制台日志使用来自后端的正确数据显示我的状态,但是当我尝试在我的 Flatlist 中呈现它时,没有什么可以显示:

<ScrollView style={styles.container}>
        {/* <Text>{this.state.restaurantInfo.restaurant.nom}</Text> */}
        <FlatList
          data={this.state.restaurantInfo}
          renderItem={this.renderRestaurantInfo}
          keyExtractor={item => `${item.restaurant.id}`}
        />
        <SectionList
          sections={productData}
          ItemSeparatorComponent={this.renderSeparator}
          renderItem={this.renderRestaurantDetail}
          renderSectionHeader={({section: {header}}) => (
            <Text style={styles.sectionHeader}>{header}</Text>
          )}
          keyExtractor={(item, index) => `${item.id}` + index}
          ref={ref => (this.sectionListRef = ref)}
          getItemLayout={this.getItemLayout}
        />
      </ScrollView>

所以我尝试像在 getRestaurantInfo() 方法中一样在 Text 组件中简单地显示餐厅的名称,但如果我不删除它,它将返回未定义。

渲染方法renderRestaurantInfo()

  renderRestaurantInfo = ({item}) => (
    <View style={styles.containerRestaurantInfo}>
      {console.log('item : ', item)}
      <ItemRestaurantInfo
        // image={item.restaurant.image}
        title={item.restaurant.nom}
        description={item.restaurant.description}
        categories={item.restaurant.categorie}
        adress={item.restaurant.adresse.rue1}
        scheduleBeginning={item.restaurant.horaires.crenaux.hDebut}
        scheduleEnd={item.restaurant.horaires.crenaux.hFin}
      />
    </View>
  )

最后是ItemRestaurantInfo 组件:

ItemRestaurantInfo = ({
  image,
  title,
  categories,
  adress,
  description,
  scheduleBeginning,
  scheduleEnd,
}) => {
  return (
    <View>
      {/* <Image source={image} style={styles.topImage} /> */}
      <View style={{padding: 15}}>
        <Text style={styles.restaurantTitle}>{title}</Text>
        <Text style={styles.restaurantInfoText}>{`${categories}`}</Text>
        <View style={styles.viewInRow}>
          <Image
            style={{margin: 5}}
            source={require('../../assets/icons/map-pin.png')}
          />
          <Text style={styles.restaurantInfoText}>{adress}</Text>
        </View>
        <Text style={styles.restaurantInfoText}>{description}</Text>
        <View style={styles.viewInRow}>
          <Image
            style={{margin: 5}}
            source={require('../../assets/icons/calendar.png')}
          />
          <Text style={styles.restaurantInfoText}>{scheduleBeginning} - {scheduleEnd}</Text>
        </View>
      </View>
    </View>
  )
}

【问题讨论】:

    标签: reactjs react-native react-native-flatlist


    【解决方案1】:

    你忘记在你的 FlatList renderItem 中传递 item

    <FlatList
       data={this.state.restaurantInfo}
       renderItem={({item}) => this.renderRestaurantInfo(item)}
       ...
    />
    

    你也可以返回一个组件而不是方法:

    const RenderItems = ({ title }) => {
      return (
        <View>
          <Text>{title}</Text>
        </View>
      );
    }
    
    ...
    
    // Pass the component to your FlatList
    <FlatList
       data={YOURDATA}
       renderItem={({ item }) => <RenderItems title={item.title} />}
       ...
    />
    
    

    你的SectionList也一样


    编辑:使用condeSandbox 获取数据的示例。

    【讨论】:

    • 好的,但是在另一个组件中我没有使用 ({item}) => this.renderRestaurantInfo(item) 语法,我仍然可以在前面渲染我的数据,例如:&lt;FlatList initialNumToRender={2} data={this.state.restaurantData} renderItem={this.renderRestaurantItem} keyExtractor={item =&gt; ${item.id}} /&gt;
    • 你说的我也添加了,但我仍然没有显示任何数据。
    • 请看官方example
    • 这是一个codeSandBox 示例。
    • 非常感谢您抽出宝贵时间,但我已尝试使用您的代码,但它仍然无法正常工作,奇怪的是它使用硬编码值并且没有 (item) => this.renderRestaurantInfo(项目),但现在我的数据来自后端,我没有显示任何内容。我检查了我的状态 restaurantInfo: [] 是否正确填充并且没有问题,我的所有数据都已正确存储,但是当显示它时,什么都没有显示...
    【解决方案2】:

    好的,我终于找到了解决方案,这是因为当我在后端调用中使用 setState 时,状态中的数组 restaurantInfo 被转换为对象......所以在 flatList 的渲染方法中没有数据.

    旧代码

    getRestaurantInfo = async () => {
        try {
          let res = await axios({
            method: 'get',
            url: `${environment.apiDevUrl}/restaurant/${this.state.restaurantId}`,
          }) 
          this.setState({
            restaurantInfo: res.data,
          })
        } catch (error) {
          console.error(error)
        }
      }
    

    新代码

     getRestaurantInfo = async () => {
        try {
          let res = await axios({
            method: 'get',
            url: `${environment.apiDevUrl}/restaurant/${this.state.restaurantId}`,
          })
          let newArray = [...this.state.restaurantInfo];
          newArray[0] = res.data
          this.setState({
            restaurantInfo: newArray,
          })
          console.log('state dans getResturantinfo:',this.state.restaurantInfo);
        } catch (error) {
          console.error(error)
        }
      }
    

    使用这种语法,它会强制做出反应以保持数组。最后没有必要使用这种语法:renderItem={({item}) =&gt; this.renderRestaurantInfo(item)}

    在我的代码中,我保持这样:

    <FlatList
              data={this.state.restaurantInfo}
              renderItem={this.renderRestaurantInfo}
              keyExtractor={item => `${item.restaurant.id}`}
            />
    

    【讨论】:

      猜你喜欢
      • 2019-05-15
      • 1970-01-01
      • 2020-12-15
      • 1970-01-01
      • 1970-01-01
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多