React Native iPhone应用Fetch POST API返回空数组但Postman调用正常问题求助
问题原因
- Redux Thunk 调用逻辑错误:未使用
dispatch触发getDeviceInfo返回的thunk函数,仅直接调用getDeviceInfo()只会生成一个待执行的函数,不会实际发起网络请求。 getDeviceInfo的函数结构不符合Redux Thunk规范:async关键字错误加在了外层action creator上,导致返回的thunk函数被包裹在Promise中,dispatch时无法正常执行内部的fetch逻辑,且AsyncStorage的异步读取逻辑放在thunk外部,执行时序容易出现异常。useEffect未配置空依赖数组,会导致页面每次渲染都重复触发请求,增加异常概率。
解决步骤
1. 修改页面触发逻辑(TargetSetUpPage.js)
首先引入useDispatch hook拿到redux的dispatch实例,用dispatch触发action,同时修正useEffect的依赖配置:
import React, { useState, useEffect } from "react"; import { useDispatch } from 'react-redux'; // 新增导入 import { StyleSheet, Text, Button, TextInput, ScrollView } from "react-native"; import * as authActions from "../../store/actions/auth"; const TargetSetUpPage = (props) => { const [targetid, setTargetId] = React.useState(""); const dispatch = useDispatch(); // 新增获取dispatch实例 const onScreenLoad = () => { dispatch(authActions.getDeviceInfo()); // 用dispatch触发action }; useEffect(() => { onScreenLoad(); }, []); // 新增空依赖数组,仅首次加载执行 // 其余原有代码保持不变
2. 修正action函数结构(auth.js的getDeviceInfo)
调整async关键字的位置,把AsyncStorage读取逻辑移到thunk内部,请求完成后记得dispatch对应action更新store数据:
export const getDeviceInfo = () => { // async移到内层thunk函数上 return async (dispatch) => { try { const useridfordevices = await AsyncStorage.getItem("userDatauserid"); const obj = JSON.parse(useridfordevices); const { userid } = obj; const userid1 = userid[0]; console.log("txtUserId is " + userid1); const formData = new FormData(); formData.append("txtUserId", userid1); const res = await fetch("https://你的实际接口地址/getDeviceInformation.php", { method: "post", body: formData, headers: { 'Accept': 'application/json' // 不要手动设置Content-Type,FormData会自动生成带boundary的正确值 } }) const result = await res.json() console.log("接口返回结果:", result); // 新增dispatch更新store,否则组件拿不到返回的数据 dispatch({ type: GETDEVICEINFO, payload: result }) } catch (err) { console.log("请求异常:", err); } }; };
3. 可选兼容方案(如果修改后仍返回空)
如果后端PHP无法正常解析multipart/form-data格式的FormData参数,可修改为x-www-form-urlencoded格式发起请求:
const res = await fetch("https://你的实际接口地址/getDeviceInformation.php", { method: "post", body: `txtUserId=${encodeURIComponent(userid1)}`, headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' } })
内容的提问来源于stack exchange,提问作者Poornima Gurudath
相关产品推荐
相关产品推荐

