简体   繁体   中英

react native fetching data from API depend on dynamic id

i am new in react native in my home screen i manage to fetch data from API using redux and axios now what i want

when i press on image it take me to EventInfo screen and display info depend on dynamic id in Postman the APIrequest POST and take this {"id":"5680"} to display the info

image from 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>)

  }

First you need to pass your id from the function which you are executing on onPress and pass your id to your navigation component

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

and after that you can get your id in eventInfo component like this.

this.props.navigation.state.params.id

Tip:: Always bind your function in your constructor if you bind inside your render function on every rendering it will create a new instance and that will cause performance issue

To get the corresponding details from the 'eventInfo' route, you must also add the id details as part of the route.

Then in the componentDidMount of the eventInfo route component , you can get the id from the route and use axios to fetch the details and render dynamically.

The specific syntax would depend on the packages being used, but this could be a general idea.

Also, if by any chance, you cannot pass the id as a route param, you could also set a global value (such as a redux-store state) to the corresponding id before navigation and from the eventInfo component, read this state and fetch from api using axios inside the componentDidMount like above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM