从 api 获取数据时在 React 中获取一个空数组

Getting an empty array in React while fetching the data from the api

我正在从 moviedb api 中获取并搜索电影。我参考了 alligator.io 教程。下面是我在其中获取数据的 Header 组件的代码。

Header.js

import React, { Component } from "react"
import { Navbar, Button, Form, FormControl } from "react-bootstrap"
import { NavLink } from "react-router-dom"
import axios from "axios"
const apiKey = process.env.REACT_APP_MOVIE_DB_API_KEY


class Header extends Component {
  state = {
    isSearching: false,
    value: "",
    movies: []
  }

  searchMovies = async val => {
    console.log("val", val)
    this.setState({ isSearching: true })
    const res = await axios(
      `https://api.themoviedb.org/3/search/movie?api_key=${apiKey}&language=en-US&query=${val}page=1&include_adult=true`
    )
    const movies = await res.data.results
    console.log(movies)
    this.setState({ movies: movies, isSearching: false })
  }

  handleChange = e => {
    const { name, value } = e.target
    this.searchMovies(value)
    this.setState({
      [name]: value
    })
  }

  handleSearch = () => {
    console.log(this.state.movies)
  }

  render() {
    return (
      <div>
        <Navbar
          bg="dark"
          expand="lg"
          style={{ justifyContent: "space-around" }}
        >
          <NavLink to="/">
            <Navbar.Brand>Movie Catalogue</Navbar.Brand>
          </NavLink>
          <Navbar.Toggle aria-controls="basic-navbar-nav" />
          <Navbar.Collapse id="basic-navbar-nav">
            <Form inline>
              <FormControl
                type="text"
                placeholder="Search"
                className="mr-sm-2"
                onChange={this.handleChange}
                name="value"
                value={this.state.value}
              />
              <Button variant="dark" onClick={this.handleSearch}>Search</Button>
            </Form>
          </Navbar.Collapse>

          <NavLink to="/popular">Popular</NavLink>
          <NavLink to="/now-playing">Now Playing</NavLink>
          <NavLink to="/top-rated">Top Rated</NavLink>
          <NavLink to="/upcoming">Upcoming</NavLink>
        </Navbar>
      </div>
    )
  }
}

export default Header

我在 movies 中得到一个空数组。当我在 handleSearch 内控制台记录 this.state.movies 时,它仍然返回一个空数组。我不知道为什么会这样。 url 一切都正确,但我得到一个空数组。

我认为您应该在 searchMovies 函数中使用 get() 方法。

const response = await axios.get('/user?ID=12345');
console.log(response);

您没有调用适当的 axios 方法。使用 get() 方法

试试这个:

 searchMovies = async val => {
    this.setState({ isSearching: true })
    const res = await axios.get(
      `https://api.themoviedb.org/3/search/movie?api_key=${apiKey}&language=en-US&query=${val}page=1&include_adult=true`;
    )
    const movies = await res.data.results;
    this.setState({ movies: movies, isSearching: false })
  }