我有一个获取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"
}
]
在targetsetupage中导入并添加调度:
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;
在store中,从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数据库中的Device数组。
Array [
Device {
"TargetId": Array [
"jtgTargetDevice1",
"jtgTargetDevice2",
],
"TargetName": Array [
"device_1",
"device_2",
],
},
]