【发布时间】:2018-06-03 16:47:49
【问题描述】:
我正在开发我的第一个复杂的 React 应用程序,并且我正在向电影 API 发出请求。我的网站允许用户在搜索栏中搜索他们正在搜索的任何电影、节目、演员等。我正在提取用户的搜索查询并将其插入到这样的 api 请求中:
export const getDetails = (id) => {
return new Promise(function(resolve, reject) {
axios.get(`https://api.themoviedb.org/3/movie/` + id +`?api_key=&language=en-US`)
.then(function(response) {
resolve(response)
})
.catch(function(error) {
reject(error)
})
})
}
我能够得到这样的数据并 console.log 它:
import React, { Component } from 'react';
import Header from '../header';
import {Link} from 'react-router-dom';
import axios from 'axios';
import Footer from '../Footer.js';
import Searchbar from '../header/searchbar.js';
import List from '../results/list';
import {getDetails} from '../api/getDetails';
class Detail extends Component {
constructor(props) {
super(props);
this.state = {
id: this.props.match.params.id,
result: null,
error: false,
}
}
componentWillMount() {
getDetails(this.state.id).then(function(response){
this.setState({result: response});
console.log(response.data.original_title);
console.log(response.data.homepage);
console.log(response.data.popularity);
console.log(response.data.release_data);
console.log(response.data.overview);
}.bind(this)).catch(function(err) {
this.setState({
result:"There was a problem loading the results. Please try again.",
error: true
})
}.bind(this))
}
render() {
return(
<div>
<Header/>
<div className="details-container">
<h2>Details: </h2>
</div>
</div>
)
}
}
export default Detail
Console.logging 它在 componentWillMount 函数中成功记录了数据,但我无法通过类似 {response.data.orginal_title) 访问渲染函数中的数据。我将如何呈现正在记录在 componentWillMount 中的数据?
【问题讨论】:
-
两件事。 1.
axios.get返回一个promise,所以你不需要将它包装在另一个promise中。 2.你在this.setState中没有使用正确的this。 -
补充 Eric 的评论:在渲染方法中,您需要参考 {this.state.result.data.original_title} 因为您将数据设置为“结果”的组件状态键
-
我对使用正确的“this”有点困惑。我不小心使用了 componentWillMount 的 this 而不是 Detail 组件中的 this?我该如何纠正呢?
-
我建议你阅读
setState和 React 中的组件状态。你打电话给setState,但你似乎不知道为什么。见reactjs.org/docs/state-and-lifecycle.html
标签: json reactjs components rendering