【问题标题】:Is there any code i'm wrong? i can not render the API有什么代码我错了吗?我无法呈现 API
【发布时间】:2019-08-27 22:37:23
【问题描述】:

我尝试将apiKey.js导出到App.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 渲染的东西

【问题讨论】:

  • 你有更完整的代码吗?我从 API(我的密钥)得到结果。还有check this
  • 显示你的 apiKey.js 文件?

标签: reactjs


【解决方案1】:

我将你调用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 })); 
  }

为了最好地反映discussion here。这就是导致您的错误的原因。

你可以检查一个简单的boilerplate here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 2012-10-31
    • 2013-01-11
    • 1970-01-01
    相关资源
    最近更新 更多