reactjs - 有什么代码我错了吗?我无法呈现 API
问题描述
我试图导出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 渲染的东西
解决方案
我改变了你调用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 }));
}
为了最好地反映这里的讨论。这就是导致您的错误的原因。
你可以在这里查看一个简单的样板
推荐阅读
- javascript - 冻结网页的父窗口的问题(打开的窗口不会在 Chrome 中加载)
- sql-server - SQL 案例评估失败?
- r - 这个 Pmin() 函数如何对列进行索引?
- git - pyCharm 会在 git commit 之前自动添加吗?
- sql - 从 Oracle 视图访问 URL
- elasticsearch - 来自 Kibana 发现选项卡的正则表达式查询对来自 logstash 的日志
- flutter - 未定义的名称“文本”
- javascript - 捕获错误:具有名称的无效表单控件不可聚焦
- pytest - 如何在pytest的模型中为自引用列创建工厂列?
- html - HTML CSS div 标签属性混淆