首页 > 解决方案 > 如何在 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>
    );
  }
}

标签: reactjsfetch

解决方案


我相信 URL 应该是

`https://wordsapiv1.p.rapidapi.com/words/${this.state.input}/definitions`

推荐阅读