在此代码中,我想直接使用函数_renderMovies
来显示数据
不喜欢
{movies? this._renderMovies(): 'Loading!' }
因为我不想展示载荷
你们是否知道如何直接使用函数_renderMovies?
我的代码:
import React, { Component } from 'react';
import L_MovieList from './L_MovieList';
import L_Ranking from './L_Ranking';
import './L_BoxOffice.css';
class L_BoxOffice extends Component {
state ={
}
constructor(props) {
super(props);
this._renderMovies = this._renderMovies.bind(this);
}
componentDidMount(){
this._getMovies();
}
_renderMovies=()=>{
const movies= this.state.movies.map((movie)=>{
console.log(movie)
return <L_Ranking
title={movie.title_english}
key={movie.id}
genres={movie.genres}
/>
})
return movies
}
_getMovies = async()=>{
const movies = await this._callApi()
this.setState({
//movies : movies
movies
})
}
_callApi=()=>{
return fetch('https://yts.am/api/v2/list_movies.json?sort_by=download_count')
.then(potato=> potato.json())
.then(json=> json.data.movies)
.catch(err=>console.log(err))
}
render() {
const{movies}=this.state;
return (
<div>
<div className={movies ? "L_BoxOffice" : "L_BoxOffice--loading"}>
<div className="L_Ranking_title">RANKING</div>
{movies? this._renderMovies(): 'Loading!' }
</div>
Box office page
<L_MovieList/>
</div>
);
}
}
export default L_BoxOffice;
答案 0 :(得分:1)
将{movies? this._renderMovies(): 'Loading!' }
替换为_this.renderMovies()
答案 1 :(得分:1)
首先,默认情况下,将movies
设置为空数组。
constructor(props) {
super(props);
this.state = { movies: [] }
this._renderMovies = this._renderMovies.bind(this);
}
之后只需渲染电影:
<div className="L_Ranking_title">RANKING</div>
{this._renderMovies()}
</div>
将空数组作为默认值,将删除三元运算符的使用情况,.map
将始终有效,因为默认情况下movies
将是可迭代的。
答案 2 :(得分:0)
使用箭头功能
就像你可以直接调用任何这样的函数
_renderMovies = ()=>{
if(true){
}else{
return 'loading...' //just an example
}
}
render(){
{this._renderMovies()}
}