首页 > 解决方案 > 有什么代码我错了吗?我无法呈现 API

问题描述

我试图导出apiKey.jsApp.js然后遇到错误

我已经删除并添加了任何不需要的 apikey 也检查了错误。

而且我仍然不明白错误在哪里

import React, { Component } from 'react';
import MovieCart from './components/MovieCart'
import './App.css';
import apiKey from './apiKey';
import { withStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';

const styles = {
  root: {
    flexGrow: 1,
  },
};


//It will be unused 
     const originalMovies =[
     {id:1,title:'Star Treck'},
     {id:2,title:'Star One'},
     {id:3,title:'Star Tol'}


   ];

class App extends Component {
  state={movies: []};

   async componentDidMount (){

    const response = await fetch(
  `    https://api.themoviedb.org/3/movie/top_rated?api_key=${apiKey}`
   );
    const json = await response.json();
    this.setState({ movies: json.results }); --> here i got an error said    movies undefined
  }
  render() {
    const {movies} = this.state;   -- i define the movies on it

    return (
       <div>
     <AppBar position="fixed" color="default">
       <Toolbar>
          <Typography variant="h6" color="inherit">
           The Lin MVP
          </Typography>
        </Toolbar>
      </AppBar>


      <div className="movies">
      {movies.map(movie => <MovieCart key={movie.id} movie={movie}/>)}
      </div>
      </div>
    );
  }
}

export default withStyles(styles)(App);

我想看看从 API 渲染的东西

标签: reactjs

解决方案


我改变了你调用componentDidMount使用的方式Promises

constructor(props) {
  super(props)
  this.state = {
    movies: []
 }
}

componentDidMount(){

    const response = fetch(`https://api.themoviedb.org/3/movie/top_rated?api_key=${youAPIKey}`)
    .then(r => r.json())
        .then(x => this.setState({ movies: x.results })); 
  }

为了最好地反映这里的讨论。这就是导致您的错误的原因。

你可以在这里查看一个简单的样板


推荐阅读