首页 > 解决方案 > 为什么无法使用 apikey 从 api 获取数据

问题描述

import React, { Component } from "react";
import Nav from "./Nav";
import SearchArea from "./SearchArea";
import MovieList from "./MovieList";

class App extends Component {
  constructor() {
    super();
    this.state = {
      movies: [],
      searchTerm: "",
    };
    this.apiKey = process.env.REACT_APP_API;
  }

  handleSubmit = (e) => {
    e.preventDeafault();

    fetch(
      `https://api.themoviedb.org/3/search/movie?api_key=${this.apiKey}&query=${this.state.searchTerm}`
    )
      .then((data) => data.json())
      .then((data) => {
        console.log(data);
        this.setState({ movies: [...data.results] });
      });
  };

  handleChange = (e) => {
    this.setState({ searchTerm: e.target.value });
  };

  render() {
    return (
      <div className="App">
        <Nav />
        <SearchArea
          handleSubmit={this.handleSubmit}
          handleChange={this.handleChange}
        />
        <MovieList movies={this.state.movies} />
      </div>
    );
  }
}

export default App;

我尝试从电影 api 进行搜索,当我开始在搜索中键入时,console.log 没有出现任何数据。我已经创建了 .env 文件。当我从搜索框中输入值时,在控制台上它只是刷新我不知道如何

REACT_APP_API=someapicodehere

标签: reactjsapifetchapi-keythemoviedb-api

解决方案


推荐阅读