React Native中如何在Fetch请求URL中插入参数?
嗨~看你是React Native新手,想实现根据分类ID加载对应帖子的功能对吧?你的代码思路是对的,但在fetch的URL拼接上有语法问题,而且在componentDidMount里没法直接用navigation,得从组件的props里取。我帮你把代码修正并完善一下:
修正后的完整代码
import React, { Component } from 'react'; import { View, Text, ActivityIndicator } from 'react-native'; import ConfigApp from './ConfigApp'; // 请根据你的实际文件路径调整 export default class PostByCategory extends Component { // 导航栏标题的配置没问题,这里保留原逻辑 static navigationOptions = ({ navigation }) => ({ title: `${navigation.state.params.Title}`, }); constructor(props) { super(props); this.state = { isLoading: true, posts: [], // 新增状态存储帖子数据 error: null, // 新增状态处理请求错误 }; } componentDidMount() { // 从组件props中获取导航对象,再拿到分类ID const { navigation } = this.props; const categoryId = navigation.state.params.IdCategory; // 用模板字符串正确拼接带参数的请求URL fetch(`${ConfigApp.URL}json/data_posts.php?category=${categoryId}`) .then((response) => { // 先校验请求是否成功 if (!response.ok) { throw new Error('请求失败,请稍后重试'); } return response.json(); // 解析返回的JSON数据 }) .then((data) => { // 请求成功后更新状态,结束加载并存储帖子数据 this.setState({ isLoading: false, posts: data, }); }) .catch((error) => { // 捕获请求过程中的错误,更新状态提示用户 this.setState({ isLoading: false, error: error.message, }); console.error('请求出错啦:', error); }); } render() { const { isLoading, posts, error } = this.state; // 加载中状态:显示加载指示器 if (isLoading) { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <ActivityIndicator size="large" color="#0000ff" /> </View> ); } // 请求错误状态:显示错误信息 if (error) { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>出错了:{error}</Text> </View> ); } // 成功获取数据:渲染帖子列表 return ( <View style={{ flex: 1, padding: 16 }}> {posts.map((post, index) => ( <View key={post.id || index} // 优先用帖子自身ID作为key,没有的话用index style={{ marginBottom: 16, padding: 12, borderWidth: 1, borderColor: '#eee' }} > <Text style={{ fontSize: 18, fontWeight: 'bold' }}>{post.title}</Text> <Text style={{ marginTop: 8 }}>{post.content}</Text> </View> ))} </View> ); } }
关键修正&优化说明:
- URL拼接错误修复:原来的写法是语法错误,改成ES6模板字符串
${ConfigApp.URL}json/data_posts.php?category=${categoryId},能正确把分类ID插入到请求参数里。 - 导航参数获取修正:在
componentDidMount里必须通过this.props.navigation拿到导航对象,不能直接用全局的navigation。 - 完善状态管理:新增了
posts存储数据、error处理错误,加上加载状态的切换,让页面逻辑更完整,用户体验更好。 - 新手小提醒:要检查
ConfigApp.URL的结尾是否带斜杠,如果你的URL是http://yourdomain.com/,拼接后就是正确的路径;如果没带斜杠,要写成${ConfigApp.URL}/json/data_posts.php,避免出现无效URL。
内容的提问来源于stack exchange,提问作者bdroid
相关产品推荐
相关产品推荐

