簡體   English   中英

從API反應本機獲取數據取決於動態ID

[英]react native fetching data from API depend on dynamic id

我是新手,在我的主屏幕中反應原生,我設法使用redux和axios從API獲取數據現在我想要的

當我按下圖像時,它會將我帶到EventInfo屏幕並顯示信息取決於Postman APIrequest POST中的動態ID並使用此{“id”:“5680”}來顯示信息

來自api的圖像

    _onLImagePressed() {
        this.props.navigation.navigate('eventInfo');

    }

  _renderListItem = ({ item }) => {
    Moment.locale('en');
    var dt = item.date;
    return (   <View style= {{flex: 1, flexDirection: 'row',marginBottom: 3}}>
        <TouchableOpacity  onPress={this._onLImagePressed.bind(this)}>
        <Image
          style={{width: 80, height: 80,margin: 5}}
          source={{uri: item.imageUrl}}
        />

        </TouchableOpacity>
      <View style={{flex: 1, justifyContent: 'center', marginLeft:5}}>
      <Text style={{fontSize: 18, color:'green', marginBottom:15}}>
      {item.id}</Text>
        <Text style={{fontSize: 16, color:'red'}}>
        {Moment(dt).format('DDD MMM YYYY')}</Text>
      </View>

      </View>)

  }

首先,您需要從onPress上執行的函數傳遞您的id,並將您的ID傳遞給導航組件

{ onPress() => this._onLImagePressed({item.id}) }
_onLImagePressed(id) {
    this.props.navigation.navigate('eventInfo', { id: id});
}

之后你可以像這樣在eventInfo組件中獲取你的id。

this.props.navigation.state.params.id

提示::如果在每次渲染時在渲染函數內部綁定,它將始終在構造函數中綁定您的函數,它將創建一個新實例,這將導致性能問題

要從'eventInfo'路徑獲取相應的詳細信息,還必須將id詳細信息添加為路徑的一部分。

然后在componentDidMount中的eventInfo route component ,你可以得到的idroute和使用axios獲取的細節和動態呈現。

具體的語法取決於所使用的包,但這可能是一個普遍的想法。

此外,如果有任何機會,您無法將id作為路由參數傳遞,您還可以在導航之前將相應的id設置為全局值(例如redux-store狀態),並從eventInfo組件中讀取此狀態並獲取來自api使用上面的componentDidMount中的axios。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM