【问题标题】:Fetch post API returning empty array in react native iphone app but working well in postman获取帖子 API 在反应原生 iphone 应用程序中返回空数组,但在邮递员中运行良好
【发布时间】:2021-12-10 01:36:32
【问题描述】:

我有一个获取 API 来从 mysql 数据库中获取值。下面是我需要从 API 获取数据的屏幕代码:

TargetSetUpPage.js:

import React, {
  useState,
  useEffect,
  useReducer,
  useSelector,
  Component,
} from "react";
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 onScreenLoad = () => {
    let action;
    action = authActions.getDeviceInfo();
  };

  useEffect(() => {
    onScreenLoad();
  });
  return (
    <ScrollView showsVerticalScrollIndicator={true}>
      <Text style={styles.headingTitle}>
        Set your target and start running:
      </Text>
      <Text style={styles.textstyle}>Target ID</Text>
      <TextInput
        style={styles.input}
        value={targetid}
        onChangeText={(targetid) => setTargetId(targetid)}
      ></TextInput>
      <Button
        title="Add"
        // onPress = {() => }
      />
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  input: {
    height: 40,
    width: "80%",
    margin: 12,
    borderWidth: 1,
    padding: 10,
  },
  headingTitle: {
    fontSize: 30,
  },
  textstyle: {
    paddingTop: 10,
    fontSize: 20,
  },
  compact: {
    flexDirection: "row",
  },
  buttonleft: {
    paddingTop: 40,
    height: 40,
    width: "80%",
  },
});

export default TargetSetUpPage;

下面是调用fetch API的store代码。

auth.js

import AsyncStorage from "@react-native-community/async-storage";
import Device from "../../model/Device";

export const LOGIN = "LOGIN";
export const LOGOUT = "LOGOUT";
export const GETDEVICEINFO = "GETDEVICEINFO";

export const login = (textemailid, textpassword) => {
  const formData = new FormData();
  formData.append("txtUemail", textemailid);
  formData.append("txtUpass", textpassword);
  return async (dispatch) => {
    fetch("https://------------------------/login.php", {
      method: "post",
      body: formData,
    })
      .then((res) => res.text())
      .then((loginresult) => {})
      .catch((err) => {
        console.log(err);
      });
    const saveDataToStorage = (loginresult) => {
      AsyncStorage.setItem(
        "userData",
        JSON.stringify({
          loginresult: loginresult,
        })
      );
    };

    dispatch({ type: LOGIN });
  };
};

export const logout = () => {
  return { type: LOGOUT };
};

export const getUserInfo = (textemailid) => {
  const formData = new FormData();
  formData.append("txtEmail", textemailid);
  return async (dispatch) => {
    fetch("https://------------------------/getUserInformation.php", {
      method: "post",
      body: formData,
    })
      .then((res) => res.json())
      .then((getuseridresult) => {
        const userid = getuseridresult.map((d) => d.id);
        saveDataToStorage(userid);
      })
      .catch((err) => {
        console.log(err);
      });
    const saveDataToStorage = async (userid) => {
      try {
        await AsyncStorage.setItem(
          "userDatauserid",
          JSON.stringify({
            userid: userid,
          })
        );
      } catch (e) {
        alert("not saved");
      }
    };
  };
};

export const getDeviceInfo = async () => {
  const useridfordevices = await AsyncStorage.getItem("userDatauserid");
  const obj = JSON.parse(useridfordevices);
  const { userid } = obj;
  var userid1 = userid[0];
  console.log("txtUserId is " + userid1);
  const formData = new FormData();
  formData.append("txtUserId", userid1);
  console.log(formData);
  return async (dispatch) => {
    fetch("https://-------------------------------/getDeviceInformation.php", {
      method: "post",
      body: formData,
    })
      .then((res) => res.json())
      .then((result) => {
        console.log("Hi" + result);
      })
      .catch((err) => {
        console.log(err);
      });
  };
};

上述 auth.js 中的 getDeviceInfo 函数没有返回任何内容。我正在发送正确的数据以获取 API,如下所示:

txtUserId is 616718042ad26
FormData {
  "_parts": Array [
      Array [
          "txtUserId",
          "616718042ad26",
        ],
      ],

在邮递员中,我得到以下 JSON 数据:

[
    {
        "targetid": "TargetDevice1",
        "targetname": "device_1",
        "userid": "616718042ad26"
    },
    {
        "targetid": "TargetDevice2",
        "targetname": "device_2",
        "userid": "616718042ad26"
    }
]

【问题讨论】:

  • 对 API 的所有调用都失败了吗?您是否需要以表单数据形式发送数据?您是否尝试将其作为stringified JSON 发送?
  • 另一个函数 getUserInfo 正在获取数据(用户 id),我将该数据发送到 getDeviceInfo 甚至没有返回任何东西 console.log('anything')。我也尝试使用 JSON.stringified但也没有 console.log() 或任何结果显示。
  • 尝试将onScreenLoad 声明为异步并等待调用getDeviceInfo()
  • const onScreenLoad = async () =>{ let action action = await authActions.getDeviceInfo( );即使这没有结果。我想知道为什么在 fetch 语句之后甚至显示 console.log()
  • 如果你在 fetch return async (dispatch) =&gt; { console.log('about to call the endpoint'); fetch(987654329@ 之前放置一个 console.log 会发生什么

标签: mysql react-native fetch


【解决方案1】:

在 TargetSetUpPage 中导入和添加调度:

TargetSetUpPage.js:

import React, {
 useState,
 useEffect,
 useReducer,
 useSelector,
 Component,
 } from "react";
 import { StyleSheet, Text, Button, TextInput, ScrollView } from "react- 
native";
import { useDispatch } from "react-redux";
import * as authActions from "../../store/actions/auth";
import AsyncStorage from '@react-native-community/async-storage';

const TargetSetUpPage = (props) => {
 const [targetid, setTargetId] = React.useState("");
 const dispatch = useDispatch();

const onScreenLoad = async() => {
const useridfordevices = await AsyncStorage.getItem("userDatauserid");
const obj = JSON.parse(useridfordevices);
const { userid } = obj;
var userid1 = userid[0];
console.log("txtUserId is " + userid1);

let action;
action = authActions.getDeviceInfo(
  userid1
);
await dispatch(action);
};

 useEffect(() => {
onScreenLoad();
 });
 return (
<ScrollView showsVerticalScrollIndicator={true}>
  <Text style={styles.headingTitle}>
    Set your target and start running:
  </Text>
  <Text style={styles.textstyle}>Target ID</Text>
  <TextInput
    style={styles.input}
    value={targetid}
    onChangeText={(targetid) => setTargetId(targetid)}
  ></TextInput>
  <Button
    title="Add"
    // onPress = {() => }
  />
</ScrollView>
);
};

const styles = StyleSheet.create({
input: {
height: 40,
width: "80%",
margin: 12,
borderWidth: 1,
padding: 10,
 },
 headingTitle: {
fontSize: 30,
 },
 textstyle: {
paddingTop: 10,
fontSize: 20,
},
compact: {
flexDirection: "row",
},
buttonleft: {
paddingTop: 40,
height: 40,
width: "80%",
},
});

 export default TargetSetUpPage;

在商店中,将操作从 getDeviceInfo 函数分派给 TargetSetUpPage.js。

auth.js:

export const getDeviceInfo =  (userid1) => {
const formData = new FormData();
formData.append("txtUserId", userid1);
return async dispatch => {
  fetch('https://----------/getDeviceInformation.php',
  {
    method:'post',
    body: formData
  })
  .then((res) => res.json())
  .then((getuserdeviceinfo) => {
    const loadDevices = [];
    loadDevices.push(
      new Device(
       getuserdeviceinfo.map((d) => d.targetid),
        getuserdeviceinfo.map((d) => d.targetname),
      )
    );
    console.log(loadDevices); 
    
  })
      .catch((err) =>{
      console.log(err);
    })
    dispatch({type:GETDEVICEINFO,availableDevice:loadDevices})
    }
    }

这将显示来自 mysql 数据库的设备数组。

Array [
Device {
"TargetId": Array [
  "jtgTargetDevice1",
  "jtgTargetDevice2",
],
"TargetName": Array [
  "device_1",
  "device_2",
 ],
 },
 ]

【讨论】:

    猜你喜欢
    • 2020-01-26
    • 2019-06-07
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    相关资源
    最近更新 更多