reactjs - 如何在 React 中自定义获取 url?
问题描述
我终于想出了如何从 API 获取数据 :) 但现在我被卡住了,因为我正在尝试更改获取请求的 URL。
我不知道如何在 URL 中使用我的输入,因为它会显示一个错误,提示输入未定义。我假设是因为从技术上讲它没有链接。我是否忽略了一些非常简单的事情?
还有一点背景;我正在尝试构建一个简单的字典 Web 应用程序,您可以在其中输入一个单词并检索定义。我目前正在为我的项目使用 WordAPI API。
import React from "react";
import "./App.css";
import ZipForm from "./ZipForm.js";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
items: null,
isLoaded: false,
input: "",
};
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onFormSubmit(input) {
this.setState({ input });
}
componentDidMount() {
const url = `https://wordsapiv1.p.rapidapi.com/words/${input}/definitions`
fetch(url, {
method: "GET",
headers: {
"x-rapidapi-host": "wordsapiv1.p.rapidapi.com",
"x-rapidapi-key": "58143f60a0msh9b238a4cf58ba29p1e28e0jsn9e523b0104ba",
},
})
.then((response) => response.json())
.then((json) => {
this.setState({
items: json,
isLoaded: true,
});
console.log(json.definitions[0].definition);
});
}
render() {
var { isLoaded, items } = this.state;
if (!isLoaded) {
return <div>Loading...</div>;
} else {
}
return (
<div>
<h1 className="tc">{items.definitions[0].definition}</h1>
<ZipForm onSubmit={this.onFormSubmit} />
</div>
);
}
}
解决方案
我相信 URL 应该是
`https://wordsapiv1.p.rapidapi.com/words/${this.state.input}/definitions`
推荐阅读
- entity-framework - 通用插入多对多(实体框架)
- python - 使用 Python 解析主机名(通过 DNS)
- msbuild - 检测 MsBuild 中 T4 文本转换的任意输入文件更改
- scala - 从 scala spark 文件的第 17 行加载 CSV 文件
- wpf - WPF:根据 Bing 地图的当前比例动态调整网格的大小
- javascript - 自定义可重用
- ibm-mobilefirst - MobileFirst - 如果上传了新版本的 IBM Apps Center,我应该怎么做
- docker - Docker 无法在代理 TLS 握手超时后提取图像
- node.js - 如果在passport-facebook节点js的数据库中找不到用户,则重定向到注册页面
- javascript - 从哪里获得 Paytm CSRF 令牌