当我尝试通过react native组件/屏幕中的按钮启动api调用时出现以下错误:
Unhandled promise rejection: TypeError: undefined is not an object (evaluating '_context.t0.response.data')]
* src\screens\NTCPDiamondScreen.js:335:17 in Button.props.onPress
* node_modules\regenerator-runtime\runtime.js:45:44 in tryCatch
* node_modules\regenerator-runtime\runtime.js:274:30 in invoke
* node_modules\regenerator-runtime\runtime.js:45:44 in tryCatch
* node_modules\regenerator-runtime\runtime.js:135:28 in invoke
* node_modules\regenerator-runtime\runtime.js:145:19 in PromiseImpl.resolve.then$argument_0
* node_modules\promise\setimmediate\core.js:37:14 in tryCallOne
* node_modules\promise\setimmediate\core.js:123:25 in setImmediate$argument_0
* node_modules\react-native\Libraries\Core\Timers\JSTimers.js:146:14 in _callTimer
* node_modules\react-native\Libraries\Core\Timers\JSTimers.js:194:17 in _callImmediatesPass
* node_modules\react-native\Libraries\Core\Timers\JSTimers.js:458:30 in callImmediates
* [native code]:null in callImmediates
* node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:407:6 in __callImmediates
* node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:143:6 in __guard$argument_0
* node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
* node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:142:17 in __guard$argument_0
* [native code]:null in flushedQueue
* [native code]:null in callFunctionReturnFlushedQueue
* node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:143:6 in __guard$argument_0
* node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
* node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:142:17 in __guard$argument_0
* [native code]:null in flushedQueue
* [native code]:null in callFunctionReturnFlushedQueue
反应本机组件:
import React, { useRef, useState, useContext, useEffect } from "react";
import {
Dimensions,
PanResponder,
View,
StyleSheet,
Text,
Alert,
AsyncStorage,
} from "react-native";
import diamondApi from "../api/diamondApi"; //file in which I have defined axios instance
const AComponentScreen = ({ navigation }) => {
//Parameteres received from a previous screen
const projectName = navigation.getParam("projectName");
const projectDescription = navigation.getParam("projectDescription");
const projectBudget = navigation.getParam("projectBudget");
const projectDuration = navigation.getParam("projectDuration");
const industry = navigation.getParam("industry");
const companyName = navigation.getParam("companyName");
const numberOfEmployees = navigation.getParam("numberOfEmployees");
const diamond = navigation.getParam("diamond");
const [projects, setProjects] = useState();
return (
<View
style={{
flex: 1,
backgroundColor: "#fff",
}}
>
<Button
title="Save and Continue"
onPress={async () => {
// initiating api call here!
try {
const result = await diamondApi.post("/projects", {
projectName,
projectDescription,
projectBudget,
projectDuration,
industry,
companyName,
numberOfEmployees,
diamond,
});
setProjects(result.data);
} catch (err) {
console.log(err.response.data);
}
if (!projects) {
console.log("loading...");
return <Text>Loading...</Text>;
} else {
console.log("Got projects!");
console.log(projects);
navigation.navigate("AnotherScreen"); //navigate to some other screen
}
}}
type="solid"
buttonStyle={{
backgroundColor: "#5CDD3F",
marginHorizontal: 15,
marginBottom: 10,
}}
titleStyle={{ fontFamily: "sans-serif-light" }}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
backgroundColor: "rgba(255,255,255,0.01)",
},
});
NTCPDiamondScreen.navigationOptions = {
title: "Create New Diamond",
};
export default AComponentScreen;
我的帖子请求:
router.post("/projects", async (req, res) => {
const {
projectName,
projectDescription,
projectBudget,
projectDuration,
industry,
companyName,
numberOfEmployees,
diamond,
} = req.body;
console.log(diamond);
//diamond is an array having structure like this: diamond[ { criteria: {a: "A", b: "B", c:"C", d:"D"} } ]
const [projectDiamond] = diamond;
const { criteria } = projectDiamond;
if (
!projectName ||
!projectDescription ||
!projectBudget ||
!projectDuration ||
!industry ||
!companyName ||
!numberOfEmployees ||
!diamond
) {
return res.status(422).send({ error: "Must provide all project details" });
}
try {
const project = new Project({
projectName,
projectDescription,
projectBudget,
projectDuration,
industry,
companyName,
numberOfEmployees,
diamond,
userId: req.user._id,
});
const recommendation = await Recommendation.find({
"diamond.criteria": criteria,
});
const projectsWithSameDiamond = await Project.find({
"diamond.criteria": criteria,
});
const projectsWithSameIndustry = await Project.find({ industry });
console.log(res);
res.json({
project,
projectsWithSameDiamond,
projectsWithSameIndustry,
recommendation,
});
} catch (err) {
res.status(422).send({ error: err.message });
}
});
以及包含axios实例的文件(diamondApi.js):
import axios from "axios";
import { AsyncStorage } from "react-native";
const instance = axios.create({
baseURL: " http://b4e79d22cea5.ngrok.io", //using ngrok to connect to the backend in react native project
});
instance.interceptors.request.use(
async (config) => {
const token = await AsyncStorage.getItem("token");
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(err) => {
return Promise.reject(err);
}
);
export default instance;
任何人都可以解释此错误的原因是什么?我想念什么或做错什么?以及如何解决?