[英]react native fetching data from API depend on dynamic id
我是新手,在我的主屏幕中反应原生,我设法使用redux和axios从API获取数据现在我想要的
当我按下图像时,它会将我带到EventInfo屏幕并显示信息取决于Postman APIrequest POST中的动态ID并使用此{“id”:“5680”}来显示信息
_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
,你可以得到的id
从route
和使用axios
获取的细节和动态呈现。
具体的语法取决于所使用的包,但这可能是一个普遍的想法。
此外,如果有任何机会,您无法将id作为路由参数传递,您还可以在导航之前将相应的id设置为全局值(例如redux-store状态),并从eventInfo组件中读取此状态并获取来自api使用上面的componentDidMount中的axios。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.