【发布时间】:2019-12-24 22:59:51
【问题描述】:
我正在尝试在 React 中使用 axios 调用 this API。我以前使用过这种方法,将请求包装在一个函数中并导出到主应用程序组件,但我只是没有得到所需的结果。
import axios from "axios";
export default axios.create({
method: "GET",
url:
"https://systran-systran-platform-for-language-processing-v1.p.rapidapi.com/resources/dictionary/lookup",
headers: {
"content-type": "application/octet-stream",
"x-rapidapi-host":
"systran-systran-platform-for-language-processing-v1.p.rapidapi.com",
"x-rapidapi-key": process.env.apiKey
},
params: {
source: "de",
target: "en"
}
});
我真的很想像这样使用导入的 axios 请求:
const addCurrentWord = async () => {
const response = await systran.get("", { params: { input: "wunderbar" } });
console.log(response.data.outputs[0].output.matches[0].targets[0].lemma);
setDefinition(response.data.outputs[0].output.matches[0].targets[0].lemma);
setWordId(prevId => prevId + 1);
setCurrentWords(prevWords => [
...prevWords,
{ id: wordId, word: enteredWord, definition: definition }
]);
};
尽管我以前多次这样做过,但我只是不知道这次出了什么问题。在这种情况下,我得到的错误似乎与 json 对象在被引用时不可用有关,但我认为 async await 意味着在 json 对象准备好使用之前不会发生任何事情。
奇怪的是,当我尝试直接在 App 组件中使用从 RapidAPI 截取的代码时,如下所示:
const axios = require("axios");
axios({
"method":"GET",
"url":"https://systran-systran-platform-for-language-processing-v1.p.rapidapi.com/translation/text/translate",
"headers":{
"content-type":"application/octet-stream",
"x-rapidapi-host":"systran-systran-platform-for-language-processing-v1.p.rapidapi.com",
"x-rapidapi-key":"4f86f3edfdmshf18247783d4906cp1eef26jsn606d81d0aed8"
},"params":{
"source":"{
source
}",
"target":"{
target
}",
"input":"{
input
}"
}
})
.then((response)=>{
console.log(response)
})
.catch((error)=>{
console.log(error)
})
我能够从 API 请求中获取正确的信息。我可以 console.log response.data.outputs[0].output.matches[0].targets[0].lemma 没有问题。
但这有一个主要缺点,就是让我的 App 组件变得庞大而笨重。我真的不希望这段代码阻塞我的 App 组件。我只是不明白这与从另一个组件导出 API 调用的其他方法有何不同。
REST API 总是让我很头疼,因为有很多我不明白的地方,我很想在这里学习一些可以帮助我的东西!
【问题讨论】: